forked from krislefeber/nestjs-dataloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
79 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
import {
CallHandler,
createParamDecorator,
ExecutionContext,
Injectable,
InternalServerErrorException,
NestInterceptor,
} from '@nestjs/common';
import { APP_INTERCEPTOR, ModuleRef, ContextIdFactory } from '@nestjs/core';
import { GqlExecutionContext } from '@nestjs/graphql';
import * as DataLoader from 'dataloader';
import { Observable } from 'rxjs';
import { idText } from 'typescript';
/**
* 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): Observable<any> {
const graphqlExecutionContext = GqlExecutionContext.create(context);
const ctx = graphqlExecutionContext.getContext();
if (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 () => {
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 = GqlExecutionContext.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);
});