Skip to content

feat(nest): add async configuration support for ORPCModule #916

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 22, 2025

Conversation

unnoq
Copy link
Owner

@unnoq unnoq commented Aug 22, 2025

Summary by CodeRabbit

  • New Features
    • NestJS integration now supports asynchronous configuration with per-request context, enabling access to the HTTP request in interceptors and middleware while preserving existing static configuration as an alternative.
  • Documentation
    • Updated NestJS setup guide to show the asynchronous configuration pattern and how to expose the request in context, including keep-alive settings.
  • Tests
    • Added tests validating async configuration, single interceptor invocation, correct propagation of request metadata (URL/headers), and keep-alive option handling.

@dosubot dosubot bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Aug 22, 2025
Copy link

vercel bot commented Aug 22, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
orpc Ready Ready Preview Comment Aug 22, 2025 3:36am

Copy link

coderabbitai bot commented Aug 22, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds ORPCModule.forRootAsync to enable async configuration via factory and DI (e.g., REQUEST), updates tests to validate per-request context propagation and keep-alive config, and updates docs to show using forRootAsync with REQUEST/express Request. No other public APIs changed.

Changes

Cohort / File(s) Summary of Changes
Nest module: Async config API
packages/nest/src/module.ts
Adds ORPCModule.forRootAsync(options) returning a DynamicModule with provider bound via useFactory/inject; exports config symbol and interceptor; keeps module global.
Tests: Async initialization & context
packages/nest/src/implement.test.ts
Adds test covering forRootAsync using REQUEST injection; verifies interceptor receives request URL/headers, single invocation, and keep-alive comment propagation; imports REQUEST and express Request types.
Docs: Nest integration guide
apps/content/docs/openapi/integrations/implement-contract-in-nest.md
Replaces forRoot example with forRootAsync using useFactory and inject: [REQUEST]; shows context: { request }, interceptors, and keep-alive interval; adds REQUEST and express Request imports; notes forRoot alternative.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant NestApp
  participant ORPCModule
  participant Factory as useFactory (forRootAsync)
  participant Interceptor as ImplementInterceptor
  participant Handler as Controller/Handler

  Client->>NestApp: HTTP request /ping
  activate NestApp
  Note over NestApp,ORPCModule: App bootstrapped with ORPCModule.forRootAsync

  NestApp->>Factory: Resolve ORPC config (inject REQUEST)
  Factory-->>NestApp: { interceptors, keepAlive, context:{ request } }

  NestApp->>Interceptor: Apply interceptor with context(request)
  Interceptor->>Handler: Invoke handler with per-request context
  Handler-->>Interceptor: Result
  Interceptor-->>NestApp: sendStandardResponse(result, keepAlive)
  NestApp-->>Client: 200 pong
  deactivate NestApp
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A hare with hooks and factory light,
As async dawn replaces night—
REQUEST in paw, it hops with glee,
Passing context per-HTTP.
"Ping!" goes the app, "Pong!" the reply—
Keep-alive whispers, packets fly.
Carrots cached; the tests comply.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/nest/forRootAsync

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @unnoq, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces asynchronous configuration support for the ORPCModule within the @orpc/nest package. This new forRootAsync method allows developers to configure the ORPC module using asynchronous operations, such as injecting dynamic values like the NestJS REQUEST object, which can then be used to provide context to ORPC interceptors and middlewares. This enhances flexibility for integrating ORPC with NestJS applications that require request-scoped or asynchronously resolved configurations.

Highlights

  • Asynchronous Module Configuration: Implemented ORPCModule.forRootAsync to enable asynchronous configuration of the ORPC module, aligning with NestJS's dynamic module patterns.
  • Request Context Integration: Demonstrated how to inject the NestJS REQUEST object into the ORPC module's context using forRootAsync, allowing request-specific data to be accessible within ORPC interceptors.
  • Comprehensive Testing: Added a dedicated test case to validate the correct behavior and data flow when using ORPCModule.forRootAsync, ensuring the new feature functions as expected.
  • Documentation Update: Updated the integration documentation to include an example of using forRootAsync for configuring the ORPCModule with request context.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces asynchronous configuration support for ORPCModule via a new forRootAsync method. The changes include the implementation of this method, corresponding tests, and documentation updates. My review focuses on aligning the new forRootAsync method with standard NestJS practices for better usability and maintainability. I've suggested an improvement to allow importing dependency modules, which is a common pattern for async modules in NestJS.

Copy link

codecov bot commented Aug 22, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copy link

pkg-pr-new bot commented Aug 22, 2025

More templates

@orpc/arktype

npm i https://pkg.pr.new/@orpc/arktype@916

@orpc/client

npm i https://pkg.pr.new/@orpc/client@916

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@916

@orpc/experimental-durable-event-iterator

npm i https://pkg.pr.new/@orpc/experimental-durable-event-iterator@916

@orpc/hey-api

npm i https://pkg.pr.new/@orpc/hey-api@916

@orpc/interop

npm i https://pkg.pr.new/@orpc/interop@916

@orpc/json-schema

npm i https://pkg.pr.new/@orpc/json-schema@916

@orpc/nest

npm i https://pkg.pr.new/@orpc/nest@916

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@916

@orpc/openapi-client

npm i https://pkg.pr.new/@orpc/openapi-client@916

@orpc/otel

npm i https://pkg.pr.new/@orpc/otel@916

@orpc/react

npm i https://pkg.pr.new/@orpc/react@916

@orpc/react-query

npm i https://pkg.pr.new/@orpc/react-query@916

@orpc/experimental-react-swr

npm i https://pkg.pr.new/@orpc/experimental-react-swr@916

@orpc/server

npm i https://pkg.pr.new/@orpc/server@916

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@916

@orpc/solid-query

npm i https://pkg.pr.new/@orpc/solid-query@916

@orpc/standard-server

npm i https://pkg.pr.new/@orpc/standard-server@916

@orpc/standard-server-aws-lambda

npm i https://pkg.pr.new/@orpc/standard-server-aws-lambda@916

@orpc/standard-server-fetch

npm i https://pkg.pr.new/@orpc/standard-server-fetch@916

@orpc/standard-server-node

npm i https://pkg.pr.new/@orpc/standard-server-node@916

@orpc/standard-server-peer

npm i https://pkg.pr.new/@orpc/standard-server-peer@916

@orpc/svelte-query

npm i https://pkg.pr.new/@orpc/svelte-query@916

@orpc/tanstack-query

npm i https://pkg.pr.new/@orpc/tanstack-query@916

@orpc/trpc

npm i https://pkg.pr.new/@orpc/trpc@916

@orpc/valibot

npm i https://pkg.pr.new/@orpc/valibot@916

@orpc/vue-colada

npm i https://pkg.pr.new/@orpc/vue-colada@916

@orpc/vue-query

npm i https://pkg.pr.new/@orpc/vue-query@916

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@916

commit: 6a3ea48

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (1)
packages/nest/src/module.ts (1)

33-39: Nice: imports support aligns with standard Nest async modules

This addresses prior feedback and enables common patterns (e.g., ConfigModule).

🧹 Nitpick comments (4)
apps/content/docs/openapi/integrations/implement-contract-in-nest.md (1)

229-229: Clarify adapter-specific typing

The comment says “if you use express adapter” which is correct for the express type, but users on Fastify should use FastifyRequest instead. Clarify with a dual example or a quick note.

Suggested tweak:

import { Request as ExpressRequest } from 'express' // Express adapter
// import type { FastifyRequest } from 'fastify'   // Fastify adapter

And in useFactory, type the param to match your adapter.

packages/nest/src/module.ts (2)

32-36: Tighten option types to Nest’s built-ins

Use ModuleMetadata['imports'] and FactoryProvider['inject'] for better type safety and IDE hints.

Apply this diff:

-  static forRootAsync(options: {
-    imports?: any[]
-    useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig
-    inject?: any[]
-  }): DynamicModule {
+  static forRootAsync(options: {
+    imports?: ModuleMetadata['imports']
+    useFactory: (...args: any[]) => Promise<ORPCModuleConfig> | ORPCModuleConfig
+    inject?: FactoryProvider['inject']
+  }): DynamicModule {

Add type-only imports:

// at top-level (type-only)
import type { ModuleMetadata, FactoryProvider } from '@nestjs/common'

48-49: Consider making global configurable (default true)

Some apps may prefer scoping this module. Expose global?: boolean in options and use options.global ?? true.

Proposed change:

-      global: true,
+      global: options['global' as never] ?? true,

And add global?: boolean to the options shape.

packages/nest/src/implement.test.ts (1)

418-464: Strengthen the async-config test to prove per-request scoping

To ensure the config factory runs per request (and isn’t cached), make a second request with different headers and assert the interceptor receives the new request object. Also assert the interceptor call count accordingly.

Apply this diff:

   it('works with ORPCModule.forRootAsync', async () => {
     const interceptor = vi.fn(({ next }) => next())
@@
     expect(res.statusCode).toEqual(200)
     expect(res.body).toEqual('pong')
@@
-    expect(interceptor).toHaveBeenCalledTimes(1)
+    expect(interceptor).toHaveBeenCalledTimes(1)
@@
     expect(sendStandardResponseSpy).toHaveBeenCalledTimes(1)
     expect(sendStandardResponseSpy).toHaveBeenCalledWith(expect.anything(), expect.anything(), expect.objectContaining({
       eventIteratorKeepAliveComment: '__TEST__',
     }))
+
+    // Make a second call to ensure the factory is evaluated per request
+    const res2 = await supertest(httpServer)
+      .post('/ping?param=second')
+      .set('x-custom', 'second')
+      .send({ hello: 'again' })
+
+    expect(res2.statusCode).toEqual(200)
+    expect(res2.body).toEqual('pong')
+
+    expect(interceptor).toHaveBeenCalledTimes(2)
+    expect(interceptor).toHaveBeenLastCalledWith(expect.objectContaining({
+      context: expect.objectContaining({
+        request: expect.objectContaining({
+          url: '/ping?param=second',
+          headers: expect.objectContaining({
+            'x-custom': 'second',
+          }),
+        }),
+      }),
+    }))
+    expect(sendStandardResponseSpy).toHaveBeenCalledTimes(2)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1a17b94 and 6a3ea48.

📒 Files selected for processing (3)
  • apps/content/docs/openapi/integrations/implement-contract-in-nest.md (1 hunks)
  • packages/nest/src/implement.test.ts (2 hunks)
  • packages/nest/src/module.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test
  • GitHub Check: publish-commit
  • GitHub Check: lint
🔇 Additional comments (2)
packages/nest/src/implement.test.ts (2)

2-5: Good: explicit typing and DI token import for per-request factory

Using type { Request } with REQUEST sets up the async factory ergonomically for Express users.


423-431: Minor: align example names with docs

Docs currently show eventIteratorKeepAliveInterval, while tests use eventIteratorKeepAliveComment. Keep tests as-is (they match the actual API) and adjust docs instead (see docs comment).

If the API indeed supports both properties, consider adding an assertion here for the interval variant as well. Otherwise, leave the test unchanged after the docs fix.

@unnoq unnoq merged commit 1e104eb into main Aug 22, 2025
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size:M This PR changes 30-99 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant