-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
80 lines (74 loc) · 2.63 KB
/
index.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import {
CallHandler,
createParamDecorator,
ExecutionContext,
Injectable,
InternalServerErrorException,
NestInterceptor,
OnModuleInit
} from '@nestjs/common';
import { APP_INTERCEPTOR, ContextIdFactory, ModuleRef } from '@nestjs/core';
import { GqlArgumentsHost } from '@nestjs/graphql';
import DataLoader from 'dataloader';
/**
* This interface will be used to generate the initial data loader.
* The concrete implementation should be added as a provider to your module.
*/
export interface NestDataLoader<ID, Type> {
/**
* Should return a new instance of dataloader each time
*/
generateDataLoader(): DataLoader<ID, Type>;
}
/**
* Context key where get loader function will be stored.
* This class should be added to your module providers like so:
* {
* provide: APP_INTERCEPTOR,
* useClass: DataLoaderInterceptor,
* },
*/
const NEST_LOADER_CONTEXT_KEY: string = "NEST_LOADER_CONTEXT_KEY";
@Injectable()
export class DataLoaderInterceptor implements NestInterceptor {
constructor(private readonly moduleRef: ModuleRef) { }
/**
* @inheritdoc
*/
intercept(context: ExecutionContext, next: CallHandler) {
const graphqlExecutionContext = GqlArgumentsHost.create(context);
const ctx = graphqlExecutionContext.getContext();
if (ctx && ctx[NEST_LOADER_CONTEXT_KEY] === undefined) {
ctx[NEST_LOADER_CONTEXT_KEY] = {
contextId: ContextIdFactory.create(),
getLoader: (type: string) : Promise<NestDataLoader<any, any>> => {
if (ctx[type] === undefined) {
try {
ctx[type] = (async () => {
const a = await this.moduleRef.resolve(type);
return (await this.moduleRef.resolve<NestDataLoader<any, any>>(type, ctx[NEST_LOADER_CONTEXT_KEY].contextId, { strict: false }))
.generateDataLoader();
})();
} catch (e) {
throw new InternalServerErrorException(`The loader ${type} is not provided` + e);
}
}
return ctx[type];
}
};
}
return next.handle();
}
}
/**
* The decorator to be used within your graphql method.
*/
export const Loader = createParamDecorator(async (data: any, context: ExecutionContext & { [key: string]: any }) => {
const ctx: any = GqlArgumentsHost.create(context).getContext();
if (ctx[NEST_LOADER_CONTEXT_KEY] === undefined) {
throw new InternalServerErrorException(`
You should provide interceptor ${DataLoaderInterceptor.name} globally with ${APP_INTERCEPTOR}
`);
}
return await ctx[NEST_LOADER_CONTEXT_KEY].getLoader(data);
});