forked from zenstackhq/zenstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzenstack.module.ts
More file actions
55 lines (52 loc) · 2.27 KB
/
zenstack.module.ts
File metadata and controls
55 lines (52 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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,
* by default with token {@link ENHANCED_PRISMA}.
*/
@Module({})
export class ZenStackModule {
/**
* Registers the ZenStack module with the specified options.
*/
static registerAsync(options: ZenStackModuleAsyncOptions): DynamicModule {
return {
module: ZenStackModule,
global: options?.global,
imports: options.imports,
providers: [
{
provide: options.exportToken ?? ENHANCED_PRISMA,
useFactory: async (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...args: unknown[]
) => {
const { getEnhancedPrisma } = await options.useFactory(...args);
if (!getEnhancedPrisma) {
throw new Error('`getEnhancedPrisma` must be provided in the options');
}
// create a proxy to intercept all calls to the Prisma service and forward
// to the enhanced version
return new Proxy(
{},
{
get(_target, prop) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const enhancedPrisma: any = getEnhancedPrisma(prop);
if (!enhancedPrisma) {
throw new Error('`getEnhancedPrisma` must return a valid Prisma client');
}
return enhancedPrisma[prop];
},
}
);
},
inject: options.inject,
},
...(options.extraProviders ?? []),
],
exports: [options.exportToken ?? ENHANCED_PRISMA],
};
}
}