NestJS Adapter
The @zenstackhq/server/nestjs
module provides a quick way to install a ZenStack-enhanced Prisma service as a dependency injection provider onto a NestJS application.
Installation
npm install @zenstackhq/server
Registering the provider
You can register the enhanced Prisma service by importing the ZenStackModule
NestJS module.
import { ZenStackModule } from '@zenstackhq/server/nestjs';
import { enhance } from '@zenstackhq/runtime';
import { PrismaService } from './prisma.service';
@Module({
imports: [
ZenStackModule.registerAsync({
useFactory: (prisma: PrismaService) => {
return {
getEnhancedPrisma: () => enhance(prisma, { user: ... }),
};
},
inject: [PrismaService],
extraProviders: [PrismaService],
}),
],
})
export class AppModule {}
The registerAsync
API takes as input a factory function that returns a config used for creating an enhanced prisma service. The config contains a callback function where you should create and return an enhanced PrismaClient
. It'll be called each time a Prisma method is invoked.
You'll usually pass in a user context when calling enhance
inside the callback. The way how the user context is fetched depends on your authentication mechanism. You can check the NestJS quick start guide for a reference solution.
Using the enhanced Prisma service
Inside your NestJS controllers or services, you can inject the enhanced Prisma service and use it as you would with the regular Prisma service. Just use the special token name ENHANCED_PRISMA
when injecting the service.
import { ENHANCED_PRISMA } from '@zenstackhq/server/nestjs';
@Controller()
export class MyController {
constructor(
@Inject(ENHANCED_PRISMA) private readonly prismaService: PrismaService,
) {}
...
}
You can still use the regular Prisma service by injecting as usual.
API reference
ZenStackModule.registerAsync
Signature
registerAsync(options: ZenStackModuleAsyncOptions): DynamicModule;
Parameter options
interface ZenStackModuleAsyncOptions {
/**
* Optional list of imported modules that export the providers which are
* required in this module.
*/
imports?: Array<Type<any> | DynamicModule | Promise<DynamicModule> | ForwardReference>;
/**
* Whether the module is global-scoped.
*/
global?: boolean;
/**
* The token to export the enhanced Prisma service. Default is `'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[];
}
interface ZenStackModuleOptions {
/**
* A callback for getting an enhanced `PrismaClient`.
*/
getEnhancedPrisma: (model?: string | symbol) => unknown;
}