feat(server): add ApiHandlerService to handle request with NestJS - #2099

Merged
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler
May 5, 2025
Merged

feat(server): add ApiHandlerService to handle request with NestJS#2099
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler

Conversation

@ppodds

@ppoddsppodds commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

When using @zenstackhq/server with NestJS, the API handler only works with the Fastify or Express adapter and requires registering middleware during module or app initialization. This approach creates a tight dependency on the framework implementation and makes it difficult to customize routing behavior.

This PR not only restructures the NestJS adapter folder to better align with NestJS conventions, but also introduces an ApiHandlerService that users can import and use. With this service, users have the flexibility to apply the handler to specific routes as needed and gain more control over the response generated by the API handler.

Usage

post.module.ts

import{Module}from'@nestjs/common';import{PrismaService}from'./prisma.service';import{ZenStackModule,ApiHandlerService}from'@zenstackhq/server/nestjs';import{enhance}from'@zenstackhq/runtime';import{PostController}from'./post.controller';import{ClsService}from'nestjs-cls';
@Module({imports: [ZenStackModule.registerAsync({useFactory: (prisma: PrismaService,clsService: ClsService)=>{return{getEnhancedPrisma: ()=>enhance(prisma,{user: clsService.get('auth')}),};},inject: [PrismaService,ClsService],extraProviders: [PrismaService],})],controllers: [PostController],providers: [PrismaService,ApiHandlerService],})exportclassPostModule{}

post.controller.ts

import{Controller,Get,Post}from'@nestjs/common';import{ApiHandlerService}from'@zenstackhq/server/nestjs';
@Controller('post')exportclassPostController{constructor(privatereadonlyapiHandlerService: ApiHandlerService){}// should align with the route generated by API handler
@Get('findMany')asyncfindMany(){returnthis.apiHandlerService.handleRequest()}
@Post('create')asynccreate(){returnthis.apiHandlerService.handleRequest()}}

I’m happy to contribute additional tests or usage examples if needed. Suggestions or improvements are very welcome—I'm open to discussion!

@coderabbitai

coderabbitaiBot commented Apr 29, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update introduces a new ApiHandlerService for handling API requests in a NestJS environment, specifically tailored for the ZenStack framework. Several supporting interfaces and constants are added, including ApiHandlerOptions, ZenStackModuleOptions, ZenStackModuleAsyncOptions, and the ENHANCED_PRISMA token. The module's public API is expanded by re-exporting these new components. The ZenStackModule is refactored to import these entities from their new locations. Comprehensive tests are added for ApiHandlerService, covering default behavior, REST API handling, and base URL support.

Changes

File(s)Change Summary
packages/server/src/nestjs/api-handler.service.tsIntroduced ApiHandlerService, a NestJS request-scoped service for handling API requests, extracting request details, invoking handlers, and managing error responses.
packages/server/src/nestjs/interfaces/api-handler-options.interface.tsAdded ApiHandlerOptions interface extending AdapterBaseOptions with an optional baseUrl property.
packages/server/src/nestjs/interfaces/zenstack-module-options.interface.tsAdded ZenStackModuleOptions and ZenStackModuleAsyncOptions interfaces for configuring the ZenStack module, supporting both synchronous and asynchronous registration with dependency injection.
packages/server/src/nestjs/interfaces/index.tsNew file re-exporting interfaces from zenstack-module-options.interface and api-handler-options.interface for easier imports.
packages/server/src/nestjs/zenstack.constants.tsIntroduced and exported the ENHANCED_PRISMA constant as the default token for the enhanced Prisma service.
packages/server/src/nestjs/zenstack.module.tsRefactored to remove local declarations of ENHANCED_PRISMA, ZenStackModuleOptions, and ZenStackModuleAsyncOptions; now imports these from their respective modules.
packages/server/src/nestjs/index.tsUpdated to export api-handler.service and zenstack.constants in addition to the existing module export.
packages/server/tests/adapter/nestjs.test.tsAdded a test suite for ApiHandlerService with tests covering default handling, REST API handler usage, and handling of requests with a base URL.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant NestJS
participant ApiHandlerService
participant PrismaClient
participant RequestHandler
Client->>NestJS: Sends HTTP request
NestJS->>ApiHandlerService: Injects request, Prisma client, HTTP adapter
ApiHandlerService->>PrismaClient: Loads model metadata and schemas
ApiHandlerService->>RequestHandler: Invokes with request details, Prisma client, metadata, schemas
RequestHandler-->>ApiHandlerService: Returns response (body, status)
alt status >= 400
ApiHandlerService->>NestJS: Throws HttpException
else status < 400
ApiHandlerService->>NestJS: Returns response body
end
NestJS-->>Client: Sends response or error
Loading

Suggested reviewers

  • ymc9

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b35a6a8 and 2dd1cca.

📒 Files selected for processing (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 3afc53d to 09677d7CompareApril 29, 2025 07:36
@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 09677d7 to a20e743CompareApril 29, 2025 07:58
@ppodds
ppodds marked this pull request as ready for review April 29, 2025 09:33

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/server/src/nestjs/api-handler.service.ts (4)

16-16: Consider breaking long constructor line

The constructor parameter list is quite long. Consider formatting it across multiple lines for better readability.

- constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract, @Inject(REQUEST) private readonly request: unknown) {}+ constructor(+ private readonly httpAdapterHost: HttpAdapterHost,+ @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,+ @Inject(REQUEST) private readonly request: unknown+ ) {}

23-25: URL construction approach might be fragile

Prefixing with "http://" to create a valid URL works but might not handle all hostname formats. Consider using a more robust URL parsing approach.

- // prefix with http:// to make a valid url accepted by URL constructor- const url = new URL(`http://${hostname}${requestUrl}`);+ // Ensure valid URL regardless of hostname format+ const fullUrl = hostname.includes('://') ? `${hostname}${requestUrl}` : `http://${hostname}${requestUrl}`;+ const url = new URL(fullUrl);

29-29: Type safety consideration for request body

The current approach for extracting the request body uses type assertion without validation. Consider adding error handling for cases where the body property might be missing.

- const requestBody = (this.request as {body: unknown}).body;+ const requestBody = this.request && typeof this.request === 'object' && 'body' in this.request + ? (this.request as {body: unknown}).body + : undefined;

43-49: Fix typo in comment and improve error handling

There's a typo in the comment, and the error handling could be more specific about the error type.

- // if reponse code >= 400 throw nestjs HttpException+ // if response code >= 400 throw nestjs HttpException
// the error response will be generated by nestjs
// caller can use try/catch to deal with this manually also
if (response.status >= 400) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- throw new HttpException(response.body as Record<string, any>, response.status)+ throw new HttpException(+ typeof response.body === 'object' ? response.body as Record<string, any> : { message: String(response.body) },+ response.status+ )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82232d9 and e0a0e99.

⛔ Files ignored due to path filters (1)
  • packages/server/tsconfig.json is excluded by !**/*.json
📒 Files selected for processing (8)
  • packages/server/src/nestjs/api-handler.service.ts (1 hunks)
  • packages/server/src/nestjs/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.constants.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.module.ts (1 hunks)
  • packages/server/tests/adapter/nestjs.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/nestjs/api-handler.service.ts (4)
packages/server/src/nestjs/zenstack.constants.ts (1)
  • ENHANCED_PRISMA (4-4)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
  • ApiHandlerOptions (3-5)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/server/tests/adapter/nestjs.test.ts (2)
packages/server/tests/utils.ts (1)
  • schema (3-29)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
🔇 Additional comments (12)
packages/server/src/nestjs/zenstack.constants.ts (1)

1-4: Well-structured constant definition with clear documentation.

The constant is properly documented with a JSDoc comment and follows the standard naming convention for constants (uppercase with underscores). Centralizing this token in a dedicated constants file is a good practice to avoid duplication and maintain consistency across the codebase.

packages/server/src/nestjs/interfaces/index.ts (1)

1-2: Good pattern for centralizing interface exports.

Creating a dedicated index file to re-export related interfaces follows best practices for module organization. This approach simplifies imports for consumers and provides a single entry point for related interfaces, making the codebase more maintainable.

packages/server/src/nestjs/index.ts (1)

2-3: Properly expanded public API with new exports.

The addition of exports for the new ApiHandlerService and constants aligns with the PR objectives. This makes the new functionality available to consumers while maintaining a well-defined public API surface.

packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)

1-5: Well-defined interface with appropriate extension.

The ApiHandlerOptions interface correctly extends AdapterBaseOptions and adds the optional baseUrl property. This aligns with the PR objectives to provide greater flexibility for routing in NestJS environments. The interface follows TypeScript naming conventions and is cleanly implemented.

packages/server/src/nestjs/zenstack.module.ts (1)

1-3: Code organization improvement

This refactoring enhances maintainability by importing the constants and interfaces from dedicated files instead of declaring them locally in the module file. This follows NestJS best practices for modular code organization.

packages/server/src/nestjs/api-handler.service.ts (2)

14-16: The service scope is appropriately set to REQUEST

Using request-scoped injection is the correct approach for this service since it needs to handle individual HTTP requests and access the request object.


26-26: Good implementation of baseUrl handling

The conditional path slicing for baseUrl provides flexibility for route configuration, which aligns with the PR objective of allowing more control over routing behavior.

packages/server/tests/adapter/nestjs.test.ts (3)

215-271: Well-structured test for default behavior

This test case thoroughly verifies the default behavior of the ApiHandlerService, including proper mocking of dependencies and validation of the response structure.


273-365: Comprehensive test for REST API handler

This test case provides excellent coverage of the service's capability to use a custom handler with complex response formats. The response validation is thorough and helps ensure compatibility with JSON:API specifications.


367-424: Validates baseUrl functionality

This test case confirms that the baseUrl option correctly modifies path handling, which is essential for the PR's objective of providing flexibility in routing.

packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (2)

6-11: Well-defined interface with clear documentation

The ZenStackModuleOptions interface is well-designed with clear JSDoc comments. The getEnhancedPrisma method signature allows for model-specific enhancement, which provides flexibility.


16-41: Comprehensive async options interface following NestJS patterns

The ZenStackModuleAsyncOptions interface follows NestJS conventions for async module configuration. The detailed documentation and optional properties provide flexibility for different use cases.

@ymc9ymc9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Comment threadpackages/server/src/nestjs/api-handler.service.ts
@ppodds

Copy link
Copy Markdown
ContributorAuthor

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

@ymc9

ymc9 commented May 5, 2025

Copy link
Copy Markdown
Member

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?
Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

Awesome! The piece of documentation is here: https://github.com/zenstackhq/zenstack-docs/blob/main/docs/reference/server-adapters/nestjs.mdx

I'm merging this PR.

ymc9
ymc9 approved these changes May 5, 2025
@ymc9
ymc9 merged commit 49d9645 into zenstackhq:devMay 5, 2025
@coderabbitaicoderabbitaiBot mentioned this pull request May 8, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@ppodds@ymc9
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

feat(server): add ApiHandlerService to handle request with NestJS - #2099

Merged
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler
May 5, 2025
Merged

feat(server): add ApiHandlerService to handle request with NestJS#2099
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler

Conversation

@ppodds

@ppoddsppodds commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

When using @zenstackhq/server with NestJS, the API handler only works with the Fastify or Express adapter and requires registering middleware during module or app initialization. This approach creates a tight dependency on the framework implementation and makes it difficult to customize routing behavior.

This PR not only restructures the NestJS adapter folder to better align with NestJS conventions, but also introduces an ApiHandlerService that users can import and use. With this service, users have the flexibility to apply the handler to specific routes as needed and gain more control over the response generated by the API handler.

Usage

post.module.ts

import{Module}from'@nestjs/common';import{PrismaService}from'./prisma.service';import{ZenStackModule,ApiHandlerService}from'@zenstackhq/server/nestjs';import{enhance}from'@zenstackhq/runtime';import{PostController}from'./post.controller';import{ClsService}from'nestjs-cls';
@Module({imports: [ZenStackModule.registerAsync({useFactory: (prisma: PrismaService,clsService: ClsService)=>{return{getEnhancedPrisma: ()=>enhance(prisma,{user: clsService.get('auth')}),};},inject: [PrismaService,ClsService],extraProviders: [PrismaService],})],controllers: [PostController],providers: [PrismaService,ApiHandlerService],})exportclassPostModule{}

post.controller.ts

import{Controller,Get,Post}from'@nestjs/common';import{ApiHandlerService}from'@zenstackhq/server/nestjs';
@Controller('post')exportclassPostController{constructor(privatereadonlyapiHandlerService: ApiHandlerService){}// should align with the route generated by API handler
@Get('findMany')asyncfindMany(){returnthis.apiHandlerService.handleRequest()}
@Post('create')asynccreate(){returnthis.apiHandlerService.handleRequest()}}

I’m happy to contribute additional tests or usage examples if needed. Suggestions or improvements are very welcome—I'm open to discussion!

@coderabbitai

coderabbitaiBot commented Apr 29, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update introduces a new ApiHandlerService for handling API requests in a NestJS environment, specifically tailored for the ZenStack framework. Several supporting interfaces and constants are added, including ApiHandlerOptions, ZenStackModuleOptions, ZenStackModuleAsyncOptions, and the ENHANCED_PRISMA token. The module's public API is expanded by re-exporting these new components. The ZenStackModule is refactored to import these entities from their new locations. Comprehensive tests are added for ApiHandlerService, covering default behavior, REST API handling, and base URL support.

Changes

File(s)Change Summary
packages/server/src/nestjs/api-handler.service.tsIntroduced ApiHandlerService, a NestJS request-scoped service for handling API requests, extracting request details, invoking handlers, and managing error responses.
packages/server/src/nestjs/interfaces/api-handler-options.interface.tsAdded ApiHandlerOptions interface extending AdapterBaseOptions with an optional baseUrl property.
packages/server/src/nestjs/interfaces/zenstack-module-options.interface.tsAdded ZenStackModuleOptions and ZenStackModuleAsyncOptions interfaces for configuring the ZenStack module, supporting both synchronous and asynchronous registration with dependency injection.
packages/server/src/nestjs/interfaces/index.tsNew file re-exporting interfaces from zenstack-module-options.interface and api-handler-options.interface for easier imports.
packages/server/src/nestjs/zenstack.constants.tsIntroduced and exported the ENHANCED_PRISMA constant as the default token for the enhanced Prisma service.
packages/server/src/nestjs/zenstack.module.tsRefactored to remove local declarations of ENHANCED_PRISMA, ZenStackModuleOptions, and ZenStackModuleAsyncOptions; now imports these from their respective modules.
packages/server/src/nestjs/index.tsUpdated to export api-handler.service and zenstack.constants in addition to the existing module export.
packages/server/tests/adapter/nestjs.test.tsAdded a test suite for ApiHandlerService with tests covering default handling, REST API handler usage, and handling of requests with a base URL.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant NestJS
participant ApiHandlerService
participant PrismaClient
participant RequestHandler
Client->>NestJS: Sends HTTP request
NestJS->>ApiHandlerService: Injects request, Prisma client, HTTP adapter
ApiHandlerService->>PrismaClient: Loads model metadata and schemas
ApiHandlerService->>RequestHandler: Invokes with request details, Prisma client, metadata, schemas
RequestHandler-->>ApiHandlerService: Returns response (body, status)
alt status >= 400
ApiHandlerService->>NestJS: Throws HttpException
else status < 400
ApiHandlerService->>NestJS: Returns response body
end
NestJS-->>Client: Sends response or error
Loading

Suggested reviewers

  • ymc9

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b35a6a8 and 2dd1cca.

📒 Files selected for processing (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 3afc53d to 09677d7CompareApril 29, 2025 07:36
@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 09677d7 to a20e743CompareApril 29, 2025 07:58
@ppodds
ppodds marked this pull request as ready for review April 29, 2025 09:33

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/server/src/nestjs/api-handler.service.ts (4)

16-16: Consider breaking long constructor line

The constructor parameter list is quite long. Consider formatting it across multiple lines for better readability.

- constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract, @Inject(REQUEST) private readonly request: unknown) {}+ constructor(+ private readonly httpAdapterHost: HttpAdapterHost,+ @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,+ @Inject(REQUEST) private readonly request: unknown+ ) {}

23-25: URL construction approach might be fragile

Prefixing with "http://" to create a valid URL works but might not handle all hostname formats. Consider using a more robust URL parsing approach.

- // prefix with http:// to make a valid url accepted by URL constructor- const url = new URL(`http://${hostname}${requestUrl}`);+ // Ensure valid URL regardless of hostname format+ const fullUrl = hostname.includes('://') ? `${hostname}${requestUrl}` : `http://${hostname}${requestUrl}`;+ const url = new URL(fullUrl);

29-29: Type safety consideration for request body

The current approach for extracting the request body uses type assertion without validation. Consider adding error handling for cases where the body property might be missing.

- const requestBody = (this.request as {body: unknown}).body;+ const requestBody = this.request && typeof this.request === 'object' && 'body' in this.request + ? (this.request as {body: unknown}).body + : undefined;

43-49: Fix typo in comment and improve error handling

There's a typo in the comment, and the error handling could be more specific about the error type.

- // if reponse code >= 400 throw nestjs HttpException+ // if response code >= 400 throw nestjs HttpException
// the error response will be generated by nestjs
// caller can use try/catch to deal with this manually also
if (response.status >= 400) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- throw new HttpException(response.body as Record<string, any>, response.status)+ throw new HttpException(+ typeof response.body === 'object' ? response.body as Record<string, any> : { message: String(response.body) },+ response.status+ )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82232d9 and e0a0e99.

⛔ Files ignored due to path filters (1)
  • packages/server/tsconfig.json is excluded by !**/*.json
📒 Files selected for processing (8)
  • packages/server/src/nestjs/api-handler.service.ts (1 hunks)
  • packages/server/src/nestjs/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.constants.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.module.ts (1 hunks)
  • packages/server/tests/adapter/nestjs.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/nestjs/api-handler.service.ts (4)
packages/server/src/nestjs/zenstack.constants.ts (1)
  • ENHANCED_PRISMA (4-4)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
  • ApiHandlerOptions (3-5)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/server/tests/adapter/nestjs.test.ts (2)
packages/server/tests/utils.ts (1)
  • schema (3-29)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
🔇 Additional comments (12)
packages/server/src/nestjs/zenstack.constants.ts (1)

1-4: Well-structured constant definition with clear documentation.

The constant is properly documented with a JSDoc comment and follows the standard naming convention for constants (uppercase with underscores). Centralizing this token in a dedicated constants file is a good practice to avoid duplication and maintain consistency across the codebase.

packages/server/src/nestjs/interfaces/index.ts (1)

1-2: Good pattern for centralizing interface exports.

Creating a dedicated index file to re-export related interfaces follows best practices for module organization. This approach simplifies imports for consumers and provides a single entry point for related interfaces, making the codebase more maintainable.

packages/server/src/nestjs/index.ts (1)

2-3: Properly expanded public API with new exports.

The addition of exports for the new ApiHandlerService and constants aligns with the PR objectives. This makes the new functionality available to consumers while maintaining a well-defined public API surface.

packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)

1-5: Well-defined interface with appropriate extension.

The ApiHandlerOptions interface correctly extends AdapterBaseOptions and adds the optional baseUrl property. This aligns with the PR objectives to provide greater flexibility for routing in NestJS environments. The interface follows TypeScript naming conventions and is cleanly implemented.

packages/server/src/nestjs/zenstack.module.ts (1)

1-3: Code organization improvement

This refactoring enhances maintainability by importing the constants and interfaces from dedicated files instead of declaring them locally in the module file. This follows NestJS best practices for modular code organization.

packages/server/src/nestjs/api-handler.service.ts (2)

14-16: The service scope is appropriately set to REQUEST

Using request-scoped injection is the correct approach for this service since it needs to handle individual HTTP requests and access the request object.


26-26: Good implementation of baseUrl handling

The conditional path slicing for baseUrl provides flexibility for route configuration, which aligns with the PR objective of allowing more control over routing behavior.

packages/server/tests/adapter/nestjs.test.ts (3)

215-271: Well-structured test for default behavior

This test case thoroughly verifies the default behavior of the ApiHandlerService, including proper mocking of dependencies and validation of the response structure.


273-365: Comprehensive test for REST API handler

This test case provides excellent coverage of the service's capability to use a custom handler with complex response formats. The response validation is thorough and helps ensure compatibility with JSON:API specifications.


367-424: Validates baseUrl functionality

This test case confirms that the baseUrl option correctly modifies path handling, which is essential for the PR's objective of providing flexibility in routing.

packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (2)

6-11: Well-defined interface with clear documentation

The ZenStackModuleOptions interface is well-designed with clear JSDoc comments. The getEnhancedPrisma method signature allows for model-specific enhancement, which provides flexibility.


16-41: Comprehensive async options interface following NestJS patterns

The ZenStackModuleAsyncOptions interface follows NestJS conventions for async module configuration. The detailed documentation and optional properties provide flexibility for different use cases.

@ymc9ymc9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Comment threadpackages/server/src/nestjs/api-handler.service.ts
@ppodds

Copy link
Copy Markdown
ContributorAuthor

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

@ymc9

ymc9 commented May 5, 2025

Copy link
Copy Markdown
Member

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?
Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

Awesome! The piece of documentation is here: https://github.com/zenstackhq/zenstack-docs/blob/main/docs/reference/server-adapters/nestjs.mdx

I'm merging this PR.

ymc9
ymc9 approved these changes May 5, 2025
@ymc9
ymc9 merged commit 49d9645 into zenstackhq:devMay 5, 2025
@coderabbitaicoderabbitaiBot mentioned this pull request May 8, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@ppodds@ymc9
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(server): add ApiHandlerService to handle request with NestJS - #2099

Merged
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler
May 5, 2025
Merged

feat(server): add ApiHandlerService to handle request with NestJS#2099
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler

Conversation

@ppodds

@ppoddsppodds commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

When using @zenstackhq/server with NestJS, the API handler only works with the Fastify or Express adapter and requires registering middleware during module or app initialization. This approach creates a tight dependency on the framework implementation and makes it difficult to customize routing behavior.

This PR not only restructures the NestJS adapter folder to better align with NestJS conventions, but also introduces an ApiHandlerService that users can import and use. With this service, users have the flexibility to apply the handler to specific routes as needed and gain more control over the response generated by the API handler.

Usage

post.module.ts

import{Module}from'@nestjs/common';import{PrismaService}from'./prisma.service';import{ZenStackModule,ApiHandlerService}from'@zenstackhq/server/nestjs';import{enhance}from'@zenstackhq/runtime';import{PostController}from'./post.controller';import{ClsService}from'nestjs-cls';
@Module({imports: [ZenStackModule.registerAsync({useFactory: (prisma: PrismaService,clsService: ClsService)=>{return{getEnhancedPrisma: ()=>enhance(prisma,{user: clsService.get('auth')}),};},inject: [PrismaService,ClsService],extraProviders: [PrismaService],})],controllers: [PostController],providers: [PrismaService,ApiHandlerService],})exportclassPostModule{}

post.controller.ts

import{Controller,Get,Post}from'@nestjs/common';import{ApiHandlerService}from'@zenstackhq/server/nestjs';
@Controller('post')exportclassPostController{constructor(privatereadonlyapiHandlerService: ApiHandlerService){}// should align with the route generated by API handler
@Get('findMany')asyncfindMany(){returnthis.apiHandlerService.handleRequest()}
@Post('create')asynccreate(){returnthis.apiHandlerService.handleRequest()}}

I’m happy to contribute additional tests or usage examples if needed. Suggestions or improvements are very welcome—I'm open to discussion!

@coderabbitai

coderabbitaiBot commented Apr 29, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update introduces a new ApiHandlerService for handling API requests in a NestJS environment, specifically tailored for the ZenStack framework. Several supporting interfaces and constants are added, including ApiHandlerOptions, ZenStackModuleOptions, ZenStackModuleAsyncOptions, and the ENHANCED_PRISMA token. The module's public API is expanded by re-exporting these new components. The ZenStackModule is refactored to import these entities from their new locations. Comprehensive tests are added for ApiHandlerService, covering default behavior, REST API handling, and base URL support.

Changes

File(s)Change Summary
packages/server/src/nestjs/api-handler.service.tsIntroduced ApiHandlerService, a NestJS request-scoped service for handling API requests, extracting request details, invoking handlers, and managing error responses.
packages/server/src/nestjs/interfaces/api-handler-options.interface.tsAdded ApiHandlerOptions interface extending AdapterBaseOptions with an optional baseUrl property.
packages/server/src/nestjs/interfaces/zenstack-module-options.interface.tsAdded ZenStackModuleOptions and ZenStackModuleAsyncOptions interfaces for configuring the ZenStack module, supporting both synchronous and asynchronous registration with dependency injection.
packages/server/src/nestjs/interfaces/index.tsNew file re-exporting interfaces from zenstack-module-options.interface and api-handler-options.interface for easier imports.
packages/server/src/nestjs/zenstack.constants.tsIntroduced and exported the ENHANCED_PRISMA constant as the default token for the enhanced Prisma service.
packages/server/src/nestjs/zenstack.module.tsRefactored to remove local declarations of ENHANCED_PRISMA, ZenStackModuleOptions, and ZenStackModuleAsyncOptions; now imports these from their respective modules.
packages/server/src/nestjs/index.tsUpdated to export api-handler.service and zenstack.constants in addition to the existing module export.
packages/server/tests/adapter/nestjs.test.tsAdded a test suite for ApiHandlerService with tests covering default handling, REST API handler usage, and handling of requests with a base URL.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant NestJS
participant ApiHandlerService
participant PrismaClient
participant RequestHandler
Client->>NestJS: Sends HTTP request
NestJS->>ApiHandlerService: Injects request, Prisma client, HTTP adapter
ApiHandlerService->>PrismaClient: Loads model metadata and schemas
ApiHandlerService->>RequestHandler: Invokes with request details, Prisma client, metadata, schemas
RequestHandler-->>ApiHandlerService: Returns response (body, status)
alt status >= 400
ApiHandlerService->>NestJS: Throws HttpException
else status < 400
ApiHandlerService->>NestJS: Returns response body
end
NestJS-->>Client: Sends response or error
Loading

Suggested reviewers

  • ymc9

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b35a6a8 and 2dd1cca.

📒 Files selected for processing (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 3afc53d to 09677d7CompareApril 29, 2025 07:36
@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 09677d7 to a20e743CompareApril 29, 2025 07:58
@ppodds
ppodds marked this pull request as ready for review April 29, 2025 09:33

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/server/src/nestjs/api-handler.service.ts (4)

16-16: Consider breaking long constructor line

The constructor parameter list is quite long. Consider formatting it across multiple lines for better readability.

- constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract, @Inject(REQUEST) private readonly request: unknown) {}+ constructor(+ private readonly httpAdapterHost: HttpAdapterHost,+ @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,+ @Inject(REQUEST) private readonly request: unknown+ ) {}

23-25: URL construction approach might be fragile

Prefixing with "http://" to create a valid URL works but might not handle all hostname formats. Consider using a more robust URL parsing approach.

- // prefix with http:// to make a valid url accepted by URL constructor- const url = new URL(`http://${hostname}${requestUrl}`);+ // Ensure valid URL regardless of hostname format+ const fullUrl = hostname.includes('://') ? `${hostname}${requestUrl}` : `http://${hostname}${requestUrl}`;+ const url = new URL(fullUrl);

29-29: Type safety consideration for request body

The current approach for extracting the request body uses type assertion without validation. Consider adding error handling for cases where the body property might be missing.

- const requestBody = (this.request as {body: unknown}).body;+ const requestBody = this.request && typeof this.request === 'object' && 'body' in this.request + ? (this.request as {body: unknown}).body + : undefined;

43-49: Fix typo in comment and improve error handling

There's a typo in the comment, and the error handling could be more specific about the error type.

- // if reponse code >= 400 throw nestjs HttpException+ // if response code >= 400 throw nestjs HttpException
// the error response will be generated by nestjs
// caller can use try/catch to deal with this manually also
if (response.status >= 400) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- throw new HttpException(response.body as Record<string, any>, response.status)+ throw new HttpException(+ typeof response.body === 'object' ? response.body as Record<string, any> : { message: String(response.body) },+ response.status+ )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82232d9 and e0a0e99.

⛔ Files ignored due to path filters (1)
  • packages/server/tsconfig.json is excluded by !**/*.json
📒 Files selected for processing (8)
  • packages/server/src/nestjs/api-handler.service.ts (1 hunks)
  • packages/server/src/nestjs/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.constants.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.module.ts (1 hunks)
  • packages/server/tests/adapter/nestjs.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/nestjs/api-handler.service.ts (4)
packages/server/src/nestjs/zenstack.constants.ts (1)
  • ENHANCED_PRISMA (4-4)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
  • ApiHandlerOptions (3-5)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/server/tests/adapter/nestjs.test.ts (2)
packages/server/tests/utils.ts (1)
  • schema (3-29)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
🔇 Additional comments (12)
packages/server/src/nestjs/zenstack.constants.ts (1)

1-4: Well-structured constant definition with clear documentation.

The constant is properly documented with a JSDoc comment and follows the standard naming convention for constants (uppercase with underscores). Centralizing this token in a dedicated constants file is a good practice to avoid duplication and maintain consistency across the codebase.

packages/server/src/nestjs/interfaces/index.ts (1)

1-2: Good pattern for centralizing interface exports.

Creating a dedicated index file to re-export related interfaces follows best practices for module organization. This approach simplifies imports for consumers and provides a single entry point for related interfaces, making the codebase more maintainable.

packages/server/src/nestjs/index.ts (1)

2-3: Properly expanded public API with new exports.

The addition of exports for the new ApiHandlerService and constants aligns with the PR objectives. This makes the new functionality available to consumers while maintaining a well-defined public API surface.

packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)

1-5: Well-defined interface with appropriate extension.

The ApiHandlerOptions interface correctly extends AdapterBaseOptions and adds the optional baseUrl property. This aligns with the PR objectives to provide greater flexibility for routing in NestJS environments. The interface follows TypeScript naming conventions and is cleanly implemented.

packages/server/src/nestjs/zenstack.module.ts (1)

1-3: Code organization improvement

This refactoring enhances maintainability by importing the constants and interfaces from dedicated files instead of declaring them locally in the module file. This follows NestJS best practices for modular code organization.

packages/server/src/nestjs/api-handler.service.ts (2)

14-16: The service scope is appropriately set to REQUEST

Using request-scoped injection is the correct approach for this service since it needs to handle individual HTTP requests and access the request object.


26-26: Good implementation of baseUrl handling

The conditional path slicing for baseUrl provides flexibility for route configuration, which aligns with the PR objective of allowing more control over routing behavior.

packages/server/tests/adapter/nestjs.test.ts (3)

215-271: Well-structured test for default behavior

This test case thoroughly verifies the default behavior of the ApiHandlerService, including proper mocking of dependencies and validation of the response structure.


273-365: Comprehensive test for REST API handler

This test case provides excellent coverage of the service's capability to use a custom handler with complex response formats. The response validation is thorough and helps ensure compatibility with JSON:API specifications.


367-424: Validates baseUrl functionality

This test case confirms that the baseUrl option correctly modifies path handling, which is essential for the PR's objective of providing flexibility in routing.

packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (2)

6-11: Well-defined interface with clear documentation

The ZenStackModuleOptions interface is well-designed with clear JSDoc comments. The getEnhancedPrisma method signature allows for model-specific enhancement, which provides flexibility.


16-41: Comprehensive async options interface following NestJS patterns

The ZenStackModuleAsyncOptions interface follows NestJS conventions for async module configuration. The detailed documentation and optional properties provide flexibility for different use cases.

@ymc9ymc9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Comment threadpackages/server/src/nestjs/api-handler.service.ts
@ppodds

Copy link
Copy Markdown
ContributorAuthor

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

@ymc9

ymc9 commented May 5, 2025

Copy link
Copy Markdown
Member

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?
Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

Awesome! The piece of documentation is here: https://github.com/zenstackhq/zenstack-docs/blob/main/docs/reference/server-adapters/nestjs.mdx

I'm merging this PR.

ymc9
ymc9 approved these changes May 5, 2025
@ymc9
ymc9 merged commit 49d9645 into zenstackhq:devMay 5, 2025
@coderabbitaicoderabbitaiBot mentioned this pull request May 8, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@ppodds@ymc9
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(server): add ApiHandlerService to handle request with NestJS - #2099

Merged
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler
May 5, 2025
Merged

feat(server): add ApiHandlerService to handle request with NestJS#2099
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler

Conversation

@ppodds

@ppoddsppodds commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

When using @zenstackhq/server with NestJS, the API handler only works with the Fastify or Express adapter and requires registering middleware during module or app initialization. This approach creates a tight dependency on the framework implementation and makes it difficult to customize routing behavior.

This PR not only restructures the NestJS adapter folder to better align with NestJS conventions, but also introduces an ApiHandlerService that users can import and use. With this service, users have the flexibility to apply the handler to specific routes as needed and gain more control over the response generated by the API handler.

Usage

post.module.ts

import{Module}from'@nestjs/common';import{PrismaService}from'./prisma.service';import{ZenStackModule,ApiHandlerService}from'@zenstackhq/server/nestjs';import{enhance}from'@zenstackhq/runtime';import{PostController}from'./post.controller';import{ClsService}from'nestjs-cls';
@Module({imports: [ZenStackModule.registerAsync({useFactory: (prisma: PrismaService,clsService: ClsService)=>{return{getEnhancedPrisma: ()=>enhance(prisma,{user: clsService.get('auth')}),};},inject: [PrismaService,ClsService],extraProviders: [PrismaService],})],controllers: [PostController],providers: [PrismaService,ApiHandlerService],})exportclassPostModule{}

post.controller.ts

import{Controller,Get,Post}from'@nestjs/common';import{ApiHandlerService}from'@zenstackhq/server/nestjs';
@Controller('post')exportclassPostController{constructor(privatereadonlyapiHandlerService: ApiHandlerService){}// should align with the route generated by API handler
@Get('findMany')asyncfindMany(){returnthis.apiHandlerService.handleRequest()}
@Post('create')asynccreate(){returnthis.apiHandlerService.handleRequest()}}

I’m happy to contribute additional tests or usage examples if needed. Suggestions or improvements are very welcome—I'm open to discussion!

@coderabbitai

coderabbitaiBot commented Apr 29, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update introduces a new ApiHandlerService for handling API requests in a NestJS environment, specifically tailored for the ZenStack framework. Several supporting interfaces and constants are added, including ApiHandlerOptions, ZenStackModuleOptions, ZenStackModuleAsyncOptions, and the ENHANCED_PRISMA token. The module's public API is expanded by re-exporting these new components. The ZenStackModule is refactored to import these entities from their new locations. Comprehensive tests are added for ApiHandlerService, covering default behavior, REST API handling, and base URL support.

Changes

File(s)Change Summary
packages/server/src/nestjs/api-handler.service.tsIntroduced ApiHandlerService, a NestJS request-scoped service for handling API requests, extracting request details, invoking handlers, and managing error responses.
packages/server/src/nestjs/interfaces/api-handler-options.interface.tsAdded ApiHandlerOptions interface extending AdapterBaseOptions with an optional baseUrl property.
packages/server/src/nestjs/interfaces/zenstack-module-options.interface.tsAdded ZenStackModuleOptions and ZenStackModuleAsyncOptions interfaces for configuring the ZenStack module, supporting both synchronous and asynchronous registration with dependency injection.
packages/server/src/nestjs/interfaces/index.tsNew file re-exporting interfaces from zenstack-module-options.interface and api-handler-options.interface for easier imports.
packages/server/src/nestjs/zenstack.constants.tsIntroduced and exported the ENHANCED_PRISMA constant as the default token for the enhanced Prisma service.
packages/server/src/nestjs/zenstack.module.tsRefactored to remove local declarations of ENHANCED_PRISMA, ZenStackModuleOptions, and ZenStackModuleAsyncOptions; now imports these from their respective modules.
packages/server/src/nestjs/index.tsUpdated to export api-handler.service and zenstack.constants in addition to the existing module export.
packages/server/tests/adapter/nestjs.test.tsAdded a test suite for ApiHandlerService with tests covering default handling, REST API handler usage, and handling of requests with a base URL.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant NestJS
participant ApiHandlerService
participant PrismaClient
participant RequestHandler
Client->>NestJS: Sends HTTP request
NestJS->>ApiHandlerService: Injects request, Prisma client, HTTP adapter
ApiHandlerService->>PrismaClient: Loads model metadata and schemas
ApiHandlerService->>RequestHandler: Invokes with request details, Prisma client, metadata, schemas
RequestHandler-->>ApiHandlerService: Returns response (body, status)
alt status >= 400
ApiHandlerService->>NestJS: Throws HttpException
else status < 400
ApiHandlerService->>NestJS: Returns response body
end
NestJS-->>Client: Sends response or error
Loading

Suggested reviewers

  • ymc9

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b35a6a8 and 2dd1cca.

📒 Files selected for processing (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 3afc53d to 09677d7CompareApril 29, 2025 07:36
@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 09677d7 to a20e743CompareApril 29, 2025 07:58
@ppodds
ppodds marked this pull request as ready for review April 29, 2025 09:33

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/server/src/nestjs/api-handler.service.ts (4)

16-16: Consider breaking long constructor line

The constructor parameter list is quite long. Consider formatting it across multiple lines for better readability.

- constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract, @Inject(REQUEST) private readonly request: unknown) {}+ constructor(+ private readonly httpAdapterHost: HttpAdapterHost,+ @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,+ @Inject(REQUEST) private readonly request: unknown+ ) {}

23-25: URL construction approach might be fragile

Prefixing with "http://" to create a valid URL works but might not handle all hostname formats. Consider using a more robust URL parsing approach.

- // prefix with http:// to make a valid url accepted by URL constructor- const url = new URL(`http://${hostname}${requestUrl}`);+ // Ensure valid URL regardless of hostname format+ const fullUrl = hostname.includes('://') ? `${hostname}${requestUrl}` : `http://${hostname}${requestUrl}`;+ const url = new URL(fullUrl);

29-29: Type safety consideration for request body

The current approach for extracting the request body uses type assertion without validation. Consider adding error handling for cases where the body property might be missing.

- const requestBody = (this.request as {body: unknown}).body;+ const requestBody = this.request && typeof this.request === 'object' && 'body' in this.request + ? (this.request as {body: unknown}).body + : undefined;

43-49: Fix typo in comment and improve error handling

There's a typo in the comment, and the error handling could be more specific about the error type.

- // if reponse code >= 400 throw nestjs HttpException+ // if response code >= 400 throw nestjs HttpException
// the error response will be generated by nestjs
// caller can use try/catch to deal with this manually also
if (response.status >= 400) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- throw new HttpException(response.body as Record<string, any>, response.status)+ throw new HttpException(+ typeof response.body === 'object' ? response.body as Record<string, any> : { message: String(response.body) },+ response.status+ )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82232d9 and e0a0e99.

⛔ Files ignored due to path filters (1)
  • packages/server/tsconfig.json is excluded by !**/*.json
📒 Files selected for processing (8)
  • packages/server/src/nestjs/api-handler.service.ts (1 hunks)
  • packages/server/src/nestjs/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.constants.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.module.ts (1 hunks)
  • packages/server/tests/adapter/nestjs.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/nestjs/api-handler.service.ts (4)
packages/server/src/nestjs/zenstack.constants.ts (1)
  • ENHANCED_PRISMA (4-4)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
  • ApiHandlerOptions (3-5)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/server/tests/adapter/nestjs.test.ts (2)
packages/server/tests/utils.ts (1)
  • schema (3-29)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
🔇 Additional comments (12)
packages/server/src/nestjs/zenstack.constants.ts (1)

1-4: Well-structured constant definition with clear documentation.

The constant is properly documented with a JSDoc comment and follows the standard naming convention for constants (uppercase with underscores). Centralizing this token in a dedicated constants file is a good practice to avoid duplication and maintain consistency across the codebase.

packages/server/src/nestjs/interfaces/index.ts (1)

1-2: Good pattern for centralizing interface exports.

Creating a dedicated index file to re-export related interfaces follows best practices for module organization. This approach simplifies imports for consumers and provides a single entry point for related interfaces, making the codebase more maintainable.

packages/server/src/nestjs/index.ts (1)

2-3: Properly expanded public API with new exports.

The addition of exports for the new ApiHandlerService and constants aligns with the PR objectives. This makes the new functionality available to consumers while maintaining a well-defined public API surface.

packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)

1-5: Well-defined interface with appropriate extension.

The ApiHandlerOptions interface correctly extends AdapterBaseOptions and adds the optional baseUrl property. This aligns with the PR objectives to provide greater flexibility for routing in NestJS environments. The interface follows TypeScript naming conventions and is cleanly implemented.

packages/server/src/nestjs/zenstack.module.ts (1)

1-3: Code organization improvement

This refactoring enhances maintainability by importing the constants and interfaces from dedicated files instead of declaring them locally in the module file. This follows NestJS best practices for modular code organization.

packages/server/src/nestjs/api-handler.service.ts (2)

14-16: The service scope is appropriately set to REQUEST

Using request-scoped injection is the correct approach for this service since it needs to handle individual HTTP requests and access the request object.


26-26: Good implementation of baseUrl handling

The conditional path slicing for baseUrl provides flexibility for route configuration, which aligns with the PR objective of allowing more control over routing behavior.

packages/server/tests/adapter/nestjs.test.ts (3)

215-271: Well-structured test for default behavior

This test case thoroughly verifies the default behavior of the ApiHandlerService, including proper mocking of dependencies and validation of the response structure.


273-365: Comprehensive test for REST API handler

This test case provides excellent coverage of the service's capability to use a custom handler with complex response formats. The response validation is thorough and helps ensure compatibility with JSON:API specifications.


367-424: Validates baseUrl functionality

This test case confirms that the baseUrl option correctly modifies path handling, which is essential for the PR's objective of providing flexibility in routing.

packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (2)

6-11: Well-defined interface with clear documentation

The ZenStackModuleOptions interface is well-designed with clear JSDoc comments. The getEnhancedPrisma method signature allows for model-specific enhancement, which provides flexibility.


16-41: Comprehensive async options interface following NestJS patterns

The ZenStackModuleAsyncOptions interface follows NestJS conventions for async module configuration. The detailed documentation and optional properties provide flexibility for different use cases.

@ymc9ymc9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Comment threadpackages/server/src/nestjs/api-handler.service.ts
@ppodds

Copy link
Copy Markdown
ContributorAuthor

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

@ymc9

ymc9 commented May 5, 2025

Copy link
Copy Markdown
Member

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?
Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

Awesome! The piece of documentation is here: https://github.com/zenstackhq/zenstack-docs/blob/main/docs/reference/server-adapters/nestjs.mdx

I'm merging this PR.

ymc9
ymc9 approved these changes May 5, 2025
@ymc9
ymc9 merged commit 49d9645 into zenstackhq:devMay 5, 2025
@coderabbitaicoderabbitaiBot mentioned this pull request May 8, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@ppodds@ymc9
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

feat(server): add ApiHandlerService to handle request with NestJS - #2099

Merged
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler
May 5, 2025
Merged

feat(server): add ApiHandlerService to handle request with NestJS#2099
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler

Conversation

@ppodds

@ppoddsppodds commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

When using @zenstackhq/server with NestJS, the API handler only works with the Fastify or Express adapter and requires registering middleware during module or app initialization. This approach creates a tight dependency on the framework implementation and makes it difficult to customize routing behavior.

This PR not only restructures the NestJS adapter folder to better align with NestJS conventions, but also introduces an ApiHandlerService that users can import and use. With this service, users have the flexibility to apply the handler to specific routes as needed and gain more control over the response generated by the API handler.

Usage

post.module.ts

import{Module}from'@nestjs/common';import{PrismaService}from'./prisma.service';import{ZenStackModule,ApiHandlerService}from'@zenstackhq/server/nestjs';import{enhance}from'@zenstackhq/runtime';import{PostController}from'./post.controller';import{ClsService}from'nestjs-cls';
@Module({imports: [ZenStackModule.registerAsync({useFactory: (prisma: PrismaService,clsService: ClsService)=>{return{getEnhancedPrisma: ()=>enhance(prisma,{user: clsService.get('auth')}),};},inject: [PrismaService,ClsService],extraProviders: [PrismaService],})],controllers: [PostController],providers: [PrismaService,ApiHandlerService],})exportclassPostModule{}

post.controller.ts

import{Controller,Get,Post}from'@nestjs/common';import{ApiHandlerService}from'@zenstackhq/server/nestjs';
@Controller('post')exportclassPostController{constructor(privatereadonlyapiHandlerService: ApiHandlerService){}// should align with the route generated by API handler
@Get('findMany')asyncfindMany(){returnthis.apiHandlerService.handleRequest()}
@Post('create')asynccreate(){returnthis.apiHandlerService.handleRequest()}}

I’m happy to contribute additional tests or usage examples if needed. Suggestions or improvements are very welcome—I'm open to discussion!

@coderabbitai

coderabbitaiBot commented Apr 29, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update introduces a new ApiHandlerService for handling API requests in a NestJS environment, specifically tailored for the ZenStack framework. Several supporting interfaces and constants are added, including ApiHandlerOptions, ZenStackModuleOptions, ZenStackModuleAsyncOptions, and the ENHANCED_PRISMA token. The module's public API is expanded by re-exporting these new components. The ZenStackModule is refactored to import these entities from their new locations. Comprehensive tests are added for ApiHandlerService, covering default behavior, REST API handling, and base URL support.

Changes

File(s)Change Summary
packages/server/src/nestjs/api-handler.service.tsIntroduced ApiHandlerService, a NestJS request-scoped service for handling API requests, extracting request details, invoking handlers, and managing error responses.
packages/server/src/nestjs/interfaces/api-handler-options.interface.tsAdded ApiHandlerOptions interface extending AdapterBaseOptions with an optional baseUrl property.
packages/server/src/nestjs/interfaces/zenstack-module-options.interface.tsAdded ZenStackModuleOptions and ZenStackModuleAsyncOptions interfaces for configuring the ZenStack module, supporting both synchronous and asynchronous registration with dependency injection.
packages/server/src/nestjs/interfaces/index.tsNew file re-exporting interfaces from zenstack-module-options.interface and api-handler-options.interface for easier imports.
packages/server/src/nestjs/zenstack.constants.tsIntroduced and exported the ENHANCED_PRISMA constant as the default token for the enhanced Prisma service.
packages/server/src/nestjs/zenstack.module.tsRefactored to remove local declarations of ENHANCED_PRISMA, ZenStackModuleOptions, and ZenStackModuleAsyncOptions; now imports these from their respective modules.
packages/server/src/nestjs/index.tsUpdated to export api-handler.service and zenstack.constants in addition to the existing module export.
packages/server/tests/adapter/nestjs.test.tsAdded a test suite for ApiHandlerService with tests covering default handling, REST API handler usage, and handling of requests with a base URL.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant NestJS
participant ApiHandlerService
participant PrismaClient
participant RequestHandler
Client->>NestJS: Sends HTTP request
NestJS->>ApiHandlerService: Injects request, Prisma client, HTTP adapter
ApiHandlerService->>PrismaClient: Loads model metadata and schemas
ApiHandlerService->>RequestHandler: Invokes with request details, Prisma client, metadata, schemas
RequestHandler-->>ApiHandlerService: Returns response (body, status)
alt status >= 400
ApiHandlerService->>NestJS: Throws HttpException
else status < 400
ApiHandlerService->>NestJS: Returns response body
end
NestJS-->>Client: Sends response or error
Loading

Suggested reviewers

  • ymc9

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b35a6a8 and 2dd1cca.

📒 Files selected for processing (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 3afc53d to 09677d7CompareApril 29, 2025 07:36
@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 09677d7 to a20e743CompareApril 29, 2025 07:58
@ppodds
ppodds marked this pull request as ready for review April 29, 2025 09:33

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/server/src/nestjs/api-handler.service.ts (4)

16-16: Consider breaking long constructor line

The constructor parameter list is quite long. Consider formatting it across multiple lines for better readability.

- constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract, @Inject(REQUEST) private readonly request: unknown) {}+ constructor(+ private readonly httpAdapterHost: HttpAdapterHost,+ @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,+ @Inject(REQUEST) private readonly request: unknown+ ) {}

23-25: URL construction approach might be fragile

Prefixing with "http://" to create a valid URL works but might not handle all hostname formats. Consider using a more robust URL parsing approach.

- // prefix with http:// to make a valid url accepted by URL constructor- const url = new URL(`http://${hostname}${requestUrl}`);+ // Ensure valid URL regardless of hostname format+ const fullUrl = hostname.includes('://') ? `${hostname}${requestUrl}` : `http://${hostname}${requestUrl}`;+ const url = new URL(fullUrl);

29-29: Type safety consideration for request body

The current approach for extracting the request body uses type assertion without validation. Consider adding error handling for cases where the body property might be missing.

- const requestBody = (this.request as {body: unknown}).body;+ const requestBody = this.request && typeof this.request === 'object' && 'body' in this.request + ? (this.request as {body: unknown}).body + : undefined;

43-49: Fix typo in comment and improve error handling

There's a typo in the comment, and the error handling could be more specific about the error type.

- // if reponse code >= 400 throw nestjs HttpException+ // if response code >= 400 throw nestjs HttpException
// the error response will be generated by nestjs
// caller can use try/catch to deal with this manually also
if (response.status >= 400) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- throw new HttpException(response.body as Record<string, any>, response.status)+ throw new HttpException(+ typeof response.body === 'object' ? response.body as Record<string, any> : { message: String(response.body) },+ response.status+ )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82232d9 and e0a0e99.

⛔ Files ignored due to path filters (1)
  • packages/server/tsconfig.json is excluded by !**/*.json
📒 Files selected for processing (8)
  • packages/server/src/nestjs/api-handler.service.ts (1 hunks)
  • packages/server/src/nestjs/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.constants.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.module.ts (1 hunks)
  • packages/server/tests/adapter/nestjs.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/nestjs/api-handler.service.ts (4)
packages/server/src/nestjs/zenstack.constants.ts (1)
  • ENHANCED_PRISMA (4-4)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
  • ApiHandlerOptions (3-5)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/server/tests/adapter/nestjs.test.ts (2)
packages/server/tests/utils.ts (1)
  • schema (3-29)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
🔇 Additional comments (12)
packages/server/src/nestjs/zenstack.constants.ts (1)

1-4: Well-structured constant definition with clear documentation.

The constant is properly documented with a JSDoc comment and follows the standard naming convention for constants (uppercase with underscores). Centralizing this token in a dedicated constants file is a good practice to avoid duplication and maintain consistency across the codebase.

packages/server/src/nestjs/interfaces/index.ts (1)

1-2: Good pattern for centralizing interface exports.

Creating a dedicated index file to re-export related interfaces follows best practices for module organization. This approach simplifies imports for consumers and provides a single entry point for related interfaces, making the codebase more maintainable.

packages/server/src/nestjs/index.ts (1)

2-3: Properly expanded public API with new exports.

The addition of exports for the new ApiHandlerService and constants aligns with the PR objectives. This makes the new functionality available to consumers while maintaining a well-defined public API surface.

packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)

1-5: Well-defined interface with appropriate extension.

The ApiHandlerOptions interface correctly extends AdapterBaseOptions and adds the optional baseUrl property. This aligns with the PR objectives to provide greater flexibility for routing in NestJS environments. The interface follows TypeScript naming conventions and is cleanly implemented.

packages/server/src/nestjs/zenstack.module.ts (1)

1-3: Code organization improvement

This refactoring enhances maintainability by importing the constants and interfaces from dedicated files instead of declaring them locally in the module file. This follows NestJS best practices for modular code organization.

packages/server/src/nestjs/api-handler.service.ts (2)

14-16: The service scope is appropriately set to REQUEST

Using request-scoped injection is the correct approach for this service since it needs to handle individual HTTP requests and access the request object.


26-26: Good implementation of baseUrl handling

The conditional path slicing for baseUrl provides flexibility for route configuration, which aligns with the PR objective of allowing more control over routing behavior.

packages/server/tests/adapter/nestjs.test.ts (3)

215-271: Well-structured test for default behavior

This test case thoroughly verifies the default behavior of the ApiHandlerService, including proper mocking of dependencies and validation of the response structure.


273-365: Comprehensive test for REST API handler

This test case provides excellent coverage of the service's capability to use a custom handler with complex response formats. The response validation is thorough and helps ensure compatibility with JSON:API specifications.


367-424: Validates baseUrl functionality

This test case confirms that the baseUrl option correctly modifies path handling, which is essential for the PR's objective of providing flexibility in routing.

packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (2)

6-11: Well-defined interface with clear documentation

The ZenStackModuleOptions interface is well-designed with clear JSDoc comments. The getEnhancedPrisma method signature allows for model-specific enhancement, which provides flexibility.


16-41: Comprehensive async options interface following NestJS patterns

The ZenStackModuleAsyncOptions interface follows NestJS conventions for async module configuration. The detailed documentation and optional properties provide flexibility for different use cases.

@ymc9ymc9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Comment threadpackages/server/src/nestjs/api-handler.service.ts
@ppodds

Copy link
Copy Markdown
ContributorAuthor

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

@ymc9

ymc9 commented May 5, 2025

Copy link
Copy Markdown
Member

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?
Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

Awesome! The piece of documentation is here: https://github.com/zenstackhq/zenstack-docs/blob/main/docs/reference/server-adapters/nestjs.mdx

I'm merging this PR.

ymc9
ymc9 approved these changes May 5, 2025
@ymc9
ymc9 merged commit 49d9645 into zenstackhq:devMay 5, 2025
@coderabbitaicoderabbitaiBot mentioned this pull request May 8, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@ppodds@ymc9
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(server): add ApiHandlerService to handle request with NestJS - #2099

Merged
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler
May 5, 2025
Merged

feat(server): add ApiHandlerService to handle request with NestJS#2099
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler

Conversation

@ppodds

@ppoddsppodds commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

When using @zenstackhq/server with NestJS, the API handler only works with the Fastify or Express adapter and requires registering middleware during module or app initialization. This approach creates a tight dependency on the framework implementation and makes it difficult to customize routing behavior.

This PR not only restructures the NestJS adapter folder to better align with NestJS conventions, but also introduces an ApiHandlerService that users can import and use. With this service, users have the flexibility to apply the handler to specific routes as needed and gain more control over the response generated by the API handler.

Usage

post.module.ts

import{Module}from'@nestjs/common';import{PrismaService}from'./prisma.service';import{ZenStackModule,ApiHandlerService}from'@zenstackhq/server/nestjs';import{enhance}from'@zenstackhq/runtime';import{PostController}from'./post.controller';import{ClsService}from'nestjs-cls';
@Module({imports: [ZenStackModule.registerAsync({useFactory: (prisma: PrismaService,clsService: ClsService)=>{return{getEnhancedPrisma: ()=>enhance(prisma,{user: clsService.get('auth')}),};},inject: [PrismaService,ClsService],extraProviders: [PrismaService],})],controllers: [PostController],providers: [PrismaService,ApiHandlerService],})exportclassPostModule{}

post.controller.ts

import{Controller,Get,Post}from'@nestjs/common';import{ApiHandlerService}from'@zenstackhq/server/nestjs';
@Controller('post')exportclassPostController{constructor(privatereadonlyapiHandlerService: ApiHandlerService){}// should align with the route generated by API handler
@Get('findMany')asyncfindMany(){returnthis.apiHandlerService.handleRequest()}
@Post('create')asynccreate(){returnthis.apiHandlerService.handleRequest()}}

I’m happy to contribute additional tests or usage examples if needed. Suggestions or improvements are very welcome—I'm open to discussion!

@coderabbitai

coderabbitaiBot commented Apr 29, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update introduces a new ApiHandlerService for handling API requests in a NestJS environment, specifically tailored for the ZenStack framework. Several supporting interfaces and constants are added, including ApiHandlerOptions, ZenStackModuleOptions, ZenStackModuleAsyncOptions, and the ENHANCED_PRISMA token. The module's public API is expanded by re-exporting these new components. The ZenStackModule is refactored to import these entities from their new locations. Comprehensive tests are added for ApiHandlerService, covering default behavior, REST API handling, and base URL support.

Changes

File(s)Change Summary
packages/server/src/nestjs/api-handler.service.tsIntroduced ApiHandlerService, a NestJS request-scoped service for handling API requests, extracting request details, invoking handlers, and managing error responses.
packages/server/src/nestjs/interfaces/api-handler-options.interface.tsAdded ApiHandlerOptions interface extending AdapterBaseOptions with an optional baseUrl property.
packages/server/src/nestjs/interfaces/zenstack-module-options.interface.tsAdded ZenStackModuleOptions and ZenStackModuleAsyncOptions interfaces for configuring the ZenStack module, supporting both synchronous and asynchronous registration with dependency injection.
packages/server/src/nestjs/interfaces/index.tsNew file re-exporting interfaces from zenstack-module-options.interface and api-handler-options.interface for easier imports.
packages/server/src/nestjs/zenstack.constants.tsIntroduced and exported the ENHANCED_PRISMA constant as the default token for the enhanced Prisma service.
packages/server/src/nestjs/zenstack.module.tsRefactored to remove local declarations of ENHANCED_PRISMA, ZenStackModuleOptions, and ZenStackModuleAsyncOptions; now imports these from their respective modules.
packages/server/src/nestjs/index.tsUpdated to export api-handler.service and zenstack.constants in addition to the existing module export.
packages/server/tests/adapter/nestjs.test.tsAdded a test suite for ApiHandlerService with tests covering default handling, REST API handler usage, and handling of requests with a base URL.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant NestJS
participant ApiHandlerService
participant PrismaClient
participant RequestHandler
Client->>NestJS: Sends HTTP request
NestJS->>ApiHandlerService: Injects request, Prisma client, HTTP adapter
ApiHandlerService->>PrismaClient: Loads model metadata and schemas
ApiHandlerService->>RequestHandler: Invokes with request details, Prisma client, metadata, schemas
RequestHandler-->>ApiHandlerService: Returns response (body, status)
alt status >= 400
ApiHandlerService->>NestJS: Throws HttpException
else status < 400
ApiHandlerService->>NestJS: Returns response body
end
NestJS-->>Client: Sends response or error
Loading

Suggested reviewers

  • ymc9

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b35a6a8 and 2dd1cca.

📒 Files selected for processing (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 3afc53d to 09677d7CompareApril 29, 2025 07:36
@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 09677d7 to a20e743CompareApril 29, 2025 07:58
@ppodds
ppodds marked this pull request as ready for review April 29, 2025 09:33

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/server/src/nestjs/api-handler.service.ts (4)

16-16: Consider breaking long constructor line

The constructor parameter list is quite long. Consider formatting it across multiple lines for better readability.

- constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract, @Inject(REQUEST) private readonly request: unknown) {}+ constructor(+ private readonly httpAdapterHost: HttpAdapterHost,+ @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,+ @Inject(REQUEST) private readonly request: unknown+ ) {}

23-25: URL construction approach might be fragile

Prefixing with "http://" to create a valid URL works but might not handle all hostname formats. Consider using a more robust URL parsing approach.

- // prefix with http:// to make a valid url accepted by URL constructor- const url = new URL(`http://${hostname}${requestUrl}`);+ // Ensure valid URL regardless of hostname format+ const fullUrl = hostname.includes('://') ? `${hostname}${requestUrl}` : `http://${hostname}${requestUrl}`;+ const url = new URL(fullUrl);

29-29: Type safety consideration for request body

The current approach for extracting the request body uses type assertion without validation. Consider adding error handling for cases where the body property might be missing.

- const requestBody = (this.request as {body: unknown}).body;+ const requestBody = this.request && typeof this.request === 'object' && 'body' in this.request + ? (this.request as {body: unknown}).body + : undefined;

43-49: Fix typo in comment and improve error handling

There's a typo in the comment, and the error handling could be more specific about the error type.

- // if reponse code >= 400 throw nestjs HttpException+ // if response code >= 400 throw nestjs HttpException
// the error response will be generated by nestjs
// caller can use try/catch to deal with this manually also
if (response.status >= 400) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- throw new HttpException(response.body as Record<string, any>, response.status)+ throw new HttpException(+ typeof response.body === 'object' ? response.body as Record<string, any> : { message: String(response.body) },+ response.status+ )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82232d9 and e0a0e99.

⛔ Files ignored due to path filters (1)
  • packages/server/tsconfig.json is excluded by !**/*.json
📒 Files selected for processing (8)
  • packages/server/src/nestjs/api-handler.service.ts (1 hunks)
  • packages/server/src/nestjs/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.constants.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.module.ts (1 hunks)
  • packages/server/tests/adapter/nestjs.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/nestjs/api-handler.service.ts (4)
packages/server/src/nestjs/zenstack.constants.ts (1)
  • ENHANCED_PRISMA (4-4)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
  • ApiHandlerOptions (3-5)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/server/tests/adapter/nestjs.test.ts (2)
packages/server/tests/utils.ts (1)
  • schema (3-29)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
🔇 Additional comments (12)
packages/server/src/nestjs/zenstack.constants.ts (1)

1-4: Well-structured constant definition with clear documentation.

The constant is properly documented with a JSDoc comment and follows the standard naming convention for constants (uppercase with underscores). Centralizing this token in a dedicated constants file is a good practice to avoid duplication and maintain consistency across the codebase.

packages/server/src/nestjs/interfaces/index.ts (1)

1-2: Good pattern for centralizing interface exports.

Creating a dedicated index file to re-export related interfaces follows best practices for module organization. This approach simplifies imports for consumers and provides a single entry point for related interfaces, making the codebase more maintainable.

packages/server/src/nestjs/index.ts (1)

2-3: Properly expanded public API with new exports.

The addition of exports for the new ApiHandlerService and constants aligns with the PR objectives. This makes the new functionality available to consumers while maintaining a well-defined public API surface.

packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)

1-5: Well-defined interface with appropriate extension.

The ApiHandlerOptions interface correctly extends AdapterBaseOptions and adds the optional baseUrl property. This aligns with the PR objectives to provide greater flexibility for routing in NestJS environments. The interface follows TypeScript naming conventions and is cleanly implemented.

packages/server/src/nestjs/zenstack.module.ts (1)

1-3: Code organization improvement

This refactoring enhances maintainability by importing the constants and interfaces from dedicated files instead of declaring them locally in the module file. This follows NestJS best practices for modular code organization.

packages/server/src/nestjs/api-handler.service.ts (2)

14-16: The service scope is appropriately set to REQUEST

Using request-scoped injection is the correct approach for this service since it needs to handle individual HTTP requests and access the request object.


26-26: Good implementation of baseUrl handling

The conditional path slicing for baseUrl provides flexibility for route configuration, which aligns with the PR objective of allowing more control over routing behavior.

packages/server/tests/adapter/nestjs.test.ts (3)

215-271: Well-structured test for default behavior

This test case thoroughly verifies the default behavior of the ApiHandlerService, including proper mocking of dependencies and validation of the response structure.


273-365: Comprehensive test for REST API handler

This test case provides excellent coverage of the service's capability to use a custom handler with complex response formats. The response validation is thorough and helps ensure compatibility with JSON:API specifications.


367-424: Validates baseUrl functionality

This test case confirms that the baseUrl option correctly modifies path handling, which is essential for the PR's objective of providing flexibility in routing.

packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (2)

6-11: Well-defined interface with clear documentation

The ZenStackModuleOptions interface is well-designed with clear JSDoc comments. The getEnhancedPrisma method signature allows for model-specific enhancement, which provides flexibility.


16-41: Comprehensive async options interface following NestJS patterns

The ZenStackModuleAsyncOptions interface follows NestJS conventions for async module configuration. The detailed documentation and optional properties provide flexibility for different use cases.

@ymc9ymc9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Comment threadpackages/server/src/nestjs/api-handler.service.ts
@ppodds

Copy link
Copy Markdown
ContributorAuthor

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

@ymc9

ymc9 commented May 5, 2025

Copy link
Copy Markdown
Member

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?
Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

Awesome! The piece of documentation is here: https://github.com/zenstackhq/zenstack-docs/blob/main/docs/reference/server-adapters/nestjs.mdx

I'm merging this PR.

ymc9
ymc9 approved these changes May 5, 2025
@ymc9
ymc9 merged commit 49d9645 into zenstackhq:devMay 5, 2025
@coderabbitaicoderabbitaiBot mentioned this pull request May 8, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@ppodds@ymc9
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(server): add ApiHandlerService to handle request with NestJS - #2099

Merged
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler
May 5, 2025
Merged

feat(server): add ApiHandlerService to handle request with NestJS#2099
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler

Conversation

@ppodds

@ppoddsppodds commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

When using @zenstackhq/server with NestJS, the API handler only works with the Fastify or Express adapter and requires registering middleware during module or app initialization. This approach creates a tight dependency on the framework implementation and makes it difficult to customize routing behavior.

This PR not only restructures the NestJS adapter folder to better align with NestJS conventions, but also introduces an ApiHandlerService that users can import and use. With this service, users have the flexibility to apply the handler to specific routes as needed and gain more control over the response generated by the API handler.

Usage

post.module.ts

import{Module}from'@nestjs/common';import{PrismaService}from'./prisma.service';import{ZenStackModule,ApiHandlerService}from'@zenstackhq/server/nestjs';import{enhance}from'@zenstackhq/runtime';import{PostController}from'./post.controller';import{ClsService}from'nestjs-cls';
@Module({imports: [ZenStackModule.registerAsync({useFactory: (prisma: PrismaService,clsService: ClsService)=>{return{getEnhancedPrisma: ()=>enhance(prisma,{user: clsService.get('auth')}),};},inject: [PrismaService,ClsService],extraProviders: [PrismaService],})],controllers: [PostController],providers: [PrismaService,ApiHandlerService],})exportclassPostModule{}

post.controller.ts

import{Controller,Get,Post}from'@nestjs/common';import{ApiHandlerService}from'@zenstackhq/server/nestjs';
@Controller('post')exportclassPostController{constructor(privatereadonlyapiHandlerService: ApiHandlerService){}// should align with the route generated by API handler
@Get('findMany')asyncfindMany(){returnthis.apiHandlerService.handleRequest()}
@Post('create')asynccreate(){returnthis.apiHandlerService.handleRequest()}}

I’m happy to contribute additional tests or usage examples if needed. Suggestions or improvements are very welcome—I'm open to discussion!

@coderabbitai

coderabbitaiBot commented Apr 29, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update introduces a new ApiHandlerService for handling API requests in a NestJS environment, specifically tailored for the ZenStack framework. Several supporting interfaces and constants are added, including ApiHandlerOptions, ZenStackModuleOptions, ZenStackModuleAsyncOptions, and the ENHANCED_PRISMA token. The module's public API is expanded by re-exporting these new components. The ZenStackModule is refactored to import these entities from their new locations. Comprehensive tests are added for ApiHandlerService, covering default behavior, REST API handling, and base URL support.

Changes

File(s)Change Summary
packages/server/src/nestjs/api-handler.service.tsIntroduced ApiHandlerService, a NestJS request-scoped service for handling API requests, extracting request details, invoking handlers, and managing error responses.
packages/server/src/nestjs/interfaces/api-handler-options.interface.tsAdded ApiHandlerOptions interface extending AdapterBaseOptions with an optional baseUrl property.
packages/server/src/nestjs/interfaces/zenstack-module-options.interface.tsAdded ZenStackModuleOptions and ZenStackModuleAsyncOptions interfaces for configuring the ZenStack module, supporting both synchronous and asynchronous registration with dependency injection.
packages/server/src/nestjs/interfaces/index.tsNew file re-exporting interfaces from zenstack-module-options.interface and api-handler-options.interface for easier imports.
packages/server/src/nestjs/zenstack.constants.tsIntroduced and exported the ENHANCED_PRISMA constant as the default token for the enhanced Prisma service.
packages/server/src/nestjs/zenstack.module.tsRefactored to remove local declarations of ENHANCED_PRISMA, ZenStackModuleOptions, and ZenStackModuleAsyncOptions; now imports these from their respective modules.
packages/server/src/nestjs/index.tsUpdated to export api-handler.service and zenstack.constants in addition to the existing module export.
packages/server/tests/adapter/nestjs.test.tsAdded a test suite for ApiHandlerService with tests covering default handling, REST API handler usage, and handling of requests with a base URL.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant NestJS
participant ApiHandlerService
participant PrismaClient
participant RequestHandler
Client->>NestJS: Sends HTTP request
NestJS->>ApiHandlerService: Injects request, Prisma client, HTTP adapter
ApiHandlerService->>PrismaClient: Loads model metadata and schemas
ApiHandlerService->>RequestHandler: Invokes with request details, Prisma client, metadata, schemas
RequestHandler-->>ApiHandlerService: Returns response (body, status)
alt status >= 400
ApiHandlerService->>NestJS: Throws HttpException
else status < 400
ApiHandlerService->>NestJS: Returns response body
end
NestJS-->>Client: Sends response or error
Loading

Suggested reviewers

  • ymc9

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b35a6a8 and 2dd1cca.

📒 Files selected for processing (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 3afc53d to 09677d7CompareApril 29, 2025 07:36
@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 09677d7 to a20e743CompareApril 29, 2025 07:58
@ppodds
ppodds marked this pull request as ready for review April 29, 2025 09:33

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/server/src/nestjs/api-handler.service.ts (4)

16-16: Consider breaking long constructor line

The constructor parameter list is quite long. Consider formatting it across multiple lines for better readability.

- constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract, @Inject(REQUEST) private readonly request: unknown) {}+ constructor(+ private readonly httpAdapterHost: HttpAdapterHost,+ @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,+ @Inject(REQUEST) private readonly request: unknown+ ) {}

23-25: URL construction approach might be fragile

Prefixing with "http://" to create a valid URL works but might not handle all hostname formats. Consider using a more robust URL parsing approach.

- // prefix with http:// to make a valid url accepted by URL constructor- const url = new URL(`http://${hostname}${requestUrl}`);+ // Ensure valid URL regardless of hostname format+ const fullUrl = hostname.includes('://') ? `${hostname}${requestUrl}` : `http://${hostname}${requestUrl}`;+ const url = new URL(fullUrl);

29-29: Type safety consideration for request body

The current approach for extracting the request body uses type assertion without validation. Consider adding error handling for cases where the body property might be missing.

- const requestBody = (this.request as {body: unknown}).body;+ const requestBody = this.request && typeof this.request === 'object' && 'body' in this.request + ? (this.request as {body: unknown}).body + : undefined;

43-49: Fix typo in comment and improve error handling

There's a typo in the comment, and the error handling could be more specific about the error type.

- // if reponse code >= 400 throw nestjs HttpException+ // if response code >= 400 throw nestjs HttpException
// the error response will be generated by nestjs
// caller can use try/catch to deal with this manually also
if (response.status >= 400) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- throw new HttpException(response.body as Record<string, any>, response.status)+ throw new HttpException(+ typeof response.body === 'object' ? response.body as Record<string, any> : { message: String(response.body) },+ response.status+ )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82232d9 and e0a0e99.

⛔ Files ignored due to path filters (1)
  • packages/server/tsconfig.json is excluded by !**/*.json
📒 Files selected for processing (8)
  • packages/server/src/nestjs/api-handler.service.ts (1 hunks)
  • packages/server/src/nestjs/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.constants.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.module.ts (1 hunks)
  • packages/server/tests/adapter/nestjs.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/nestjs/api-handler.service.ts (4)
packages/server/src/nestjs/zenstack.constants.ts (1)
  • ENHANCED_PRISMA (4-4)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
  • ApiHandlerOptions (3-5)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/server/tests/adapter/nestjs.test.ts (2)
packages/server/tests/utils.ts (1)
  • schema (3-29)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
🔇 Additional comments (12)
packages/server/src/nestjs/zenstack.constants.ts (1)

1-4: Well-structured constant definition with clear documentation.

The constant is properly documented with a JSDoc comment and follows the standard naming convention for constants (uppercase with underscores). Centralizing this token in a dedicated constants file is a good practice to avoid duplication and maintain consistency across the codebase.

packages/server/src/nestjs/interfaces/index.ts (1)

1-2: Good pattern for centralizing interface exports.

Creating a dedicated index file to re-export related interfaces follows best practices for module organization. This approach simplifies imports for consumers and provides a single entry point for related interfaces, making the codebase more maintainable.

packages/server/src/nestjs/index.ts (1)

2-3: Properly expanded public API with new exports.

The addition of exports for the new ApiHandlerService and constants aligns with the PR objectives. This makes the new functionality available to consumers while maintaining a well-defined public API surface.

packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)

1-5: Well-defined interface with appropriate extension.

The ApiHandlerOptions interface correctly extends AdapterBaseOptions and adds the optional baseUrl property. This aligns with the PR objectives to provide greater flexibility for routing in NestJS environments. The interface follows TypeScript naming conventions and is cleanly implemented.

packages/server/src/nestjs/zenstack.module.ts (1)

1-3: Code organization improvement

This refactoring enhances maintainability by importing the constants and interfaces from dedicated files instead of declaring them locally in the module file. This follows NestJS best practices for modular code organization.

packages/server/src/nestjs/api-handler.service.ts (2)

14-16: The service scope is appropriately set to REQUEST

Using request-scoped injection is the correct approach for this service since it needs to handle individual HTTP requests and access the request object.


26-26: Good implementation of baseUrl handling

The conditional path slicing for baseUrl provides flexibility for route configuration, which aligns with the PR objective of allowing more control over routing behavior.

packages/server/tests/adapter/nestjs.test.ts (3)

215-271: Well-structured test for default behavior

This test case thoroughly verifies the default behavior of the ApiHandlerService, including proper mocking of dependencies and validation of the response structure.


273-365: Comprehensive test for REST API handler

This test case provides excellent coverage of the service's capability to use a custom handler with complex response formats. The response validation is thorough and helps ensure compatibility with JSON:API specifications.


367-424: Validates baseUrl functionality

This test case confirms that the baseUrl option correctly modifies path handling, which is essential for the PR's objective of providing flexibility in routing.

packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (2)

6-11: Well-defined interface with clear documentation

The ZenStackModuleOptions interface is well-designed with clear JSDoc comments. The getEnhancedPrisma method signature allows for model-specific enhancement, which provides flexibility.


16-41: Comprehensive async options interface following NestJS patterns

The ZenStackModuleAsyncOptions interface follows NestJS conventions for async module configuration. The detailed documentation and optional properties provide flexibility for different use cases.

@ymc9ymc9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Comment threadpackages/server/src/nestjs/api-handler.service.ts
@ppodds

Copy link
Copy Markdown
ContributorAuthor

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

@ymc9

ymc9 commented May 5, 2025

Copy link
Copy Markdown
Member

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?
Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

Awesome! The piece of documentation is here: https://github.com/zenstackhq/zenstack-docs/blob/main/docs/reference/server-adapters/nestjs.mdx

I'm merging this PR.

ymc9
ymc9 approved these changes May 5, 2025
@ymc9
ymc9 merged commit 49d9645 into zenstackhq:devMay 5, 2025
@coderabbitaicoderabbitaiBot mentioned this pull request May 8, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@ppodds@ymc9
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

feat(server): add ApiHandlerService to handle request with NestJS - #2099

Merged
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler
May 5, 2025
Merged

feat(server): add ApiHandlerService to handle request with NestJS#2099
ymc9 merged 5 commits into
zenstackhq:devfrom
ppodds:feat/nestjs-api-handler

Conversation

@ppodds

@ppoddsppodds commented Apr 29, 2025

Copy link
Copy Markdown
Contributor

When using @zenstackhq/server with NestJS, the API handler only works with the Fastify or Express adapter and requires registering middleware during module or app initialization. This approach creates a tight dependency on the framework implementation and makes it difficult to customize routing behavior.

This PR not only restructures the NestJS adapter folder to better align with NestJS conventions, but also introduces an ApiHandlerService that users can import and use. With this service, users have the flexibility to apply the handler to specific routes as needed and gain more control over the response generated by the API handler.

Usage

post.module.ts

import{Module}from'@nestjs/common';import{PrismaService}from'./prisma.service';import{ZenStackModule,ApiHandlerService}from'@zenstackhq/server/nestjs';import{enhance}from'@zenstackhq/runtime';import{PostController}from'./post.controller';import{ClsService}from'nestjs-cls';
@Module({imports: [ZenStackModule.registerAsync({useFactory: (prisma: PrismaService,clsService: ClsService)=>{return{getEnhancedPrisma: ()=>enhance(prisma,{user: clsService.get('auth')}),};},inject: [PrismaService,ClsService],extraProviders: [PrismaService],})],controllers: [PostController],providers: [PrismaService,ApiHandlerService],})exportclassPostModule{}

post.controller.ts

import{Controller,Get,Post}from'@nestjs/common';import{ApiHandlerService}from'@zenstackhq/server/nestjs';
@Controller('post')exportclassPostController{constructor(privatereadonlyapiHandlerService: ApiHandlerService){}// should align with the route generated by API handler
@Get('findMany')asyncfindMany(){returnthis.apiHandlerService.handleRequest()}
@Post('create')asynccreate(){returnthis.apiHandlerService.handleRequest()}}

I’m happy to contribute additional tests or usage examples if needed. Suggestions or improvements are very welcome—I'm open to discussion!

@coderabbitai

coderabbitaiBot commented Apr 29, 2025

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This update introduces a new ApiHandlerService for handling API requests in a NestJS environment, specifically tailored for the ZenStack framework. Several supporting interfaces and constants are added, including ApiHandlerOptions, ZenStackModuleOptions, ZenStackModuleAsyncOptions, and the ENHANCED_PRISMA token. The module's public API is expanded by re-exporting these new components. The ZenStackModule is refactored to import these entities from their new locations. Comprehensive tests are added for ApiHandlerService, covering default behavior, REST API handling, and base URL support.

Changes

File(s)Change Summary
packages/server/src/nestjs/api-handler.service.tsIntroduced ApiHandlerService, a NestJS request-scoped service for handling API requests, extracting request details, invoking handlers, and managing error responses.
packages/server/src/nestjs/interfaces/api-handler-options.interface.tsAdded ApiHandlerOptions interface extending AdapterBaseOptions with an optional baseUrl property.
packages/server/src/nestjs/interfaces/zenstack-module-options.interface.tsAdded ZenStackModuleOptions and ZenStackModuleAsyncOptions interfaces for configuring the ZenStack module, supporting both synchronous and asynchronous registration with dependency injection.
packages/server/src/nestjs/interfaces/index.tsNew file re-exporting interfaces from zenstack-module-options.interface and api-handler-options.interface for easier imports.
packages/server/src/nestjs/zenstack.constants.tsIntroduced and exported the ENHANCED_PRISMA constant as the default token for the enhanced Prisma service.
packages/server/src/nestjs/zenstack.module.tsRefactored to remove local declarations of ENHANCED_PRISMA, ZenStackModuleOptions, and ZenStackModuleAsyncOptions; now imports these from their respective modules.
packages/server/src/nestjs/index.tsUpdated to export api-handler.service and zenstack.constants in addition to the existing module export.
packages/server/tests/adapter/nestjs.test.tsAdded a test suite for ApiHandlerService with tests covering default handling, REST API handler usage, and handling of requests with a base URL.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant NestJS
participant ApiHandlerService
participant PrismaClient
participant RequestHandler
Client->>NestJS: Sends HTTP request
NestJS->>ApiHandlerService: Injects request, Prisma client, HTTP adapter
ApiHandlerService->>PrismaClient: Loads model metadata and schemas
ApiHandlerService->>RequestHandler: Invokes with request details, Prisma client, metadata, schemas
RequestHandler-->>ApiHandlerService: Returns response (body, status)
alt status >= 400
ApiHandlerService->>NestJS: Throws HttpException
else status < 400
ApiHandlerService->>NestJS: Returns response body
end
NestJS-->>Client: Sends response or error
Loading

Suggested reviewers

  • ymc9

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b35a6a8 and 2dd1cca.

📒 Files selected for processing (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

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:

‼️IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 3afc53d to 09677d7CompareApril 29, 2025 07:36
@ppodds
ppoddsforce-pushed the feat/nestjs-api-handler branch from 09677d7 to a20e743CompareApril 29, 2025 07:58
@ppodds
ppodds marked this pull request as ready for review April 29, 2025 09:33

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/server/src/nestjs/api-handler.service.ts (4)

16-16: Consider breaking long constructor line

The constructor parameter list is quite long. Consider formatting it across multiple lines for better readability.

- constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract, @Inject(REQUEST) private readonly request: unknown) {}+ constructor(+ private readonly httpAdapterHost: HttpAdapterHost,+ @Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,+ @Inject(REQUEST) private readonly request: unknown+ ) {}

23-25: URL construction approach might be fragile

Prefixing with "http://" to create a valid URL works but might not handle all hostname formats. Consider using a more robust URL parsing approach.

- // prefix with http:// to make a valid url accepted by URL constructor- const url = new URL(`http://${hostname}${requestUrl}`);+ // Ensure valid URL regardless of hostname format+ const fullUrl = hostname.includes('://') ? `${hostname}${requestUrl}` : `http://${hostname}${requestUrl}`;+ const url = new URL(fullUrl);

29-29: Type safety consideration for request body

The current approach for extracting the request body uses type assertion without validation. Consider adding error handling for cases where the body property might be missing.

- const requestBody = (this.request as {body: unknown}).body;+ const requestBody = this.request && typeof this.request === 'object' && 'body' in this.request + ? (this.request as {body: unknown}).body + : undefined;

43-49: Fix typo in comment and improve error handling

There's a typo in the comment, and the error handling could be more specific about the error type.

- // if reponse code >= 400 throw nestjs HttpException+ // if response code >= 400 throw nestjs HttpException
// the error response will be generated by nestjs
// caller can use try/catch to deal with this manually also
if (response.status >= 400) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
- throw new HttpException(response.body as Record<string, any>, response.status)+ throw new HttpException(+ typeof response.body === 'object' ? response.body as Record<string, any> : { message: String(response.body) },+ response.status+ )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 82232d9 and e0a0e99.

⛔ Files ignored due to path filters (1)
  • packages/server/tsconfig.json is excluded by !**/*.json
📒 Files selected for processing (8)
  • packages/server/src/nestjs/api-handler.service.ts (1 hunks)
  • packages/server/src/nestjs/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/index.ts (1 hunks)
  • packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.constants.ts (1 hunks)
  • packages/server/src/nestjs/zenstack.module.ts (1 hunks)
  • packages/server/tests/adapter/nestjs.test.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/nestjs/api-handler.service.ts (4)
packages/server/src/nestjs/zenstack.constants.ts (1)
  • ENHANCED_PRISMA (4-4)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)
  • ApiHandlerOptions (3-5)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/server/tests/adapter/nestjs.test.ts (2)
packages/server/tests/utils.ts (1)
  • schema (3-29)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
🔇 Additional comments (12)
packages/server/src/nestjs/zenstack.constants.ts (1)

1-4: Well-structured constant definition with clear documentation.

The constant is properly documented with a JSDoc comment and follows the standard naming convention for constants (uppercase with underscores). Centralizing this token in a dedicated constants file is a good practice to avoid duplication and maintain consistency across the codebase.

packages/server/src/nestjs/interfaces/index.ts (1)

1-2: Good pattern for centralizing interface exports.

Creating a dedicated index file to re-export related interfaces follows best practices for module organization. This approach simplifies imports for consumers and provides a single entry point for related interfaces, making the codebase more maintainable.

packages/server/src/nestjs/index.ts (1)

2-3: Properly expanded public API with new exports.

The addition of exports for the new ApiHandlerService and constants aligns with the PR objectives. This makes the new functionality available to consumers while maintaining a well-defined public API surface.

packages/server/src/nestjs/interfaces/api-handler-options.interface.ts (1)

1-5: Well-defined interface with appropriate extension.

The ApiHandlerOptions interface correctly extends AdapterBaseOptions and adds the optional baseUrl property. This aligns with the PR objectives to provide greater flexibility for routing in NestJS environments. The interface follows TypeScript naming conventions and is cleanly implemented.

packages/server/src/nestjs/zenstack.module.ts (1)

1-3: Code organization improvement

This refactoring enhances maintainability by importing the constants and interfaces from dedicated files instead of declaring them locally in the module file. This follows NestJS best practices for modular code organization.

packages/server/src/nestjs/api-handler.service.ts (2)

14-16: The service scope is appropriately set to REQUEST

Using request-scoped injection is the correct approach for this service since it needs to handle individual HTTP requests and access the request object.


26-26: Good implementation of baseUrl handling

The conditional path slicing for baseUrl provides flexibility for route configuration, which aligns with the PR objective of allowing more control over routing behavior.

packages/server/tests/adapter/nestjs.test.ts (3)

215-271: Well-structured test for default behavior

This test case thoroughly verifies the default behavior of the ApiHandlerService, including proper mocking of dependencies and validation of the response structure.


273-365: Comprehensive test for REST API handler

This test case provides excellent coverage of the service's capability to use a custom handler with complex response formats. The response validation is thorough and helps ensure compatibility with JSON:API specifications.


367-424: Validates baseUrl functionality

This test case confirms that the baseUrl option correctly modifies path handling, which is essential for the PR's objective of providing flexibility in routing.

packages/server/src/nestjs/interfaces/zenstack-module-options.interface.ts (2)

6-11: Well-defined interface with clear documentation

The ZenStackModuleOptions interface is well-designed with clear JSDoc comments. The getEnhancedPrisma method signature allows for model-specific enhancement, which provides flexibility.


16-41: Comprehensive async options interface following NestJS patterns

The ZenStackModuleAsyncOptions interface follows NestJS conventions for async module configuration. The detailed documentation and optional properties provide flexibility for different use cases.

@ymc9ymc9 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Comment threadpackages/server/src/nestjs/api-handler.service.ts
@ppodds

Copy link
Copy Markdown
ContributorAuthor

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?

Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

@ymc9

ymc9 commented May 5, 2025

Copy link
Copy Markdown
Member

Hi @ppodds , many thanks for making this contribution! I think it's a good addition, with the service you can even implement a catch all route to automatically forward all requests to the underlying handler, right?
Will you be interested in changing the documentation as well? Basically after the zenstack module is registered, you can have two paths to using it: 1. directly inject the enhanced prisma client and use it in whatever service/controller you want; 2. use the api handler service to automate request handling.

Sure! I will add it after the PR has been merged.

Awesome! The piece of documentation is here: https://github.com/zenstackhq/zenstack-docs/blob/main/docs/reference/server-adapters/nestjs.mdx

I'm merging this PR.

ymc9
ymc9 approved these changes May 5, 2025
@ymc9
ymc9 merged commit 49d9645 into zenstackhq:devMay 5, 2025
@coderabbitaicoderabbitaiBot mentioned this pull request May 8, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@ppodds@ymc9