Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions packages/server/src/nestjs/api-handler.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { DbClientContract } from '@zenstackhq/runtime';
import { HttpException, Inject, Injectable, Scope } from "@nestjs/common";
import { HttpAdapterHost, REQUEST } from "@nestjs/core";
import { loadAssets } from "../shared";
import { RPCApiHandler } from '../api/rpc';
import { ENHANCED_PRISMA } from "./zenstack.constants";
import { ApiHandlerOptions } from './interfaces';

/**
* The ZenStack API handler service for NestJS. The service is used to handle API requests
* and forward them to the ZenStack API handler. It is platform agnostic and can be used
* with any HTTP adapter.
*/
@Injectable({ scope: Scope.REQUEST })
export class ApiHandlerService {
constructor(
private readonly httpAdapterHost: HttpAdapterHost,
@Inject(ENHANCED_PRISMA) private readonly prisma: DbClientContract,
@Inject(REQUEST) private readonly request: unknown
) { }

async handleRequest(options?: ApiHandlerOptions): Promise<unknown> {
const { modelMeta, zodSchemas } = loadAssets(options || {});
const requestHandler = options?.handler || RPCApiHandler();
const hostname = this.httpAdapterHost.httpAdapter.getRequestHostname(this.request);
const requestUrl = this.httpAdapterHost.httpAdapter.getRequestUrl(this.request);
// prefix with http:// to make a valid url accepted by URL constructor
const url = new URL(`http://${hostname}${requestUrl}`);
const method = this.httpAdapterHost.httpAdapter.getRequestMethod(this.request);
const path = options?.baseUrl && url.pathname.startsWith(options.baseUrl) ? url.pathname.slice(options.baseUrl.length) : url.pathname;
const searchParams = url.searchParams;
const query = Object.fromEntries(searchParams);
const requestBody = (this.request as { body: unknown }).body;

const response = await requestHandler({
method,
path,
query,
requestBody,
prisma: this.prisma,
modelMeta,
zodSchemas,
logger: options?.logger,
});

// handle handler error
// 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)
}
return response.body
}
}
2 changes: 2 additions & 0 deletions packages/server/src/nestjs/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export * from './zenstack.module';
export * from './api-handler.service';
export * from './zenstack.constants';
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { AdapterBaseOptions } from "../../types";

export interface ApiHandlerOptions extends AdapterBaseOptions {
/**
* The base URL for the API handler. This is used to determine the base path for the API requests.
* If you are using the ApiHandlerService in a route with a prefix, you should set this to the prefix.
*
* e.g.
* without baseUrl(API handler default route):
* - RPC API handler: [model]/findMany
* - RESTful API handler: /:type
*
* with baseUrl(/api/crud):
* - RPC API handler: /api/crud/[model]/findMany
* - RESTful API handler: /api/crud/:type
*/
baseUrl?: string;
}
2 changes: 2 additions & 0 deletions packages/server/src/nestjs/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './zenstack-module-options.interface'
export * from './api-handler-options.interface'
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { FactoryProvider, ModuleMetadata, Provider } from "@nestjs/common";

/**
* ZenStack module options.
*/
export interface ZenStackModuleOptions {
/**
* A callback for getting an enhanced `PrismaClient`.
*/
getEnhancedPrisma: (model?: string | symbol) => unknown;
}

/**
* ZenStack module async registration options.
*/
export interface ZenStackModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
/**
* Whether the module is global-scoped.
*/
global?: boolean;

/**
* The token to export the enhanced Prisma service. Default is {@link ENHANCED_PRISMA}.
*/
exportToken?: string;

/**
* The factory function to create the enhancement options.
*/
useFactory: (...args: unknown[]) => Promise<ZenStackModuleOptions> | ZenStackModuleOptions;

/**
* The dependencies to inject into the factory function.
*/
inject?: FactoryProvider['inject'];

/**
* Extra providers to facilitate dependency injection.
*/
extraProviders?: Provider[];
}
4 changes: 4 additions & 0 deletions packages/server/src/nestjs/zenstack.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/**
* The default token used to export the enhanced Prisma service.
*/
export const ENHANCED_PRISMA = 'ENHANCED_PRISMA';
49 changes: 3 additions & 46 deletions packages/server/src/nestjs/zenstack.module.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,6 @@
import { Module, type DynamicModule, type FactoryProvider, type ModuleMetadata, type Provider } from '@nestjs/common';

/**
* The default token used to export the enhanced Prisma service.
*/
export const ENHANCED_PRISMA = 'ENHANCED_PRISMA';

/**
* ZenStack module options.
*/
export interface ZenStackModuleOptions {
/**
* A callback for getting an enhanced `PrismaClient`.
*/
getEnhancedPrisma: (model?: string | symbol ) => unknown;
}

/**
* ZenStack module async registration options.
*/
export interface ZenStackModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
/**
* Whether the module is global-scoped.
*/
global?: boolean;

/**
* The token to export the enhanced Prisma service. Default is {@link ENHANCED_PRISMA}.
*/
exportToken?: string;

/**
* The factory function to create the enhancement options.
*/
useFactory: (...args: unknown[]) => Promise<ZenStackModuleOptions> | ZenStackModuleOptions;

/**
* The dependencies to inject into the factory function.
*/
inject?: FactoryProvider['inject'];

/**
* Extra providers to facilitate dependency injection.
*/
extraProviders?: Provider[];
}
import { Module, type DynamicModule } from '@nestjs/common';
import { ENHANCED_PRISMA } from './zenstack.constants';
import { ZenStackModuleAsyncOptions } from './interfaces';

/**
* The ZenStack module for NestJS. The module exports an enhanced Prisma service,
Expand Down
Loading
Loading