forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddlewares-injector.ts
58 lines (51 loc) · 2.55 KB
/
middlewares-injector.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
import 'reflect-metadata';
import iterate from 'iterare';
import { NestContainer, InstanceWrapper } from '@nestjs/core/injector/container';
import { NestGateway } from './index';
import { GATEWAY_MIDDLEWARES } from './constants';
import { UnknownModuleException } from '@nestjs/core/errors/exceptions/unknown-module.exception';
import { Injectable } from '@nestjs/common/interfaces/injectable.interface';
import { RuntimeException } from '@nestjs/core/errors/exceptions/runtime.exception';
import { GatewayMiddleware } from './interfaces/gateway-middleware.interface';
import { isUndefined, isFunction, isNil } from '@nestjs/common/utils/shared.utils';
import { ApplicationConfig } from '@nestjs/core/application-config';
export class MiddlewaresInjector {
constructor(
private readonly container: NestContainer,
private readonly config: ApplicationConfig) {}
public inject(server, instance: NestGateway, module: string) {
const adapter = this.config.getIoAdapter();
if (!adapter.bindMiddleware) {
return;
}
const opaqueTokens = this.reflectMiddlewaresTokens(instance);
const modules = this.container.getModules();
if (!modules.has(module)) {
throw new UnknownModuleException();
}
const { components } = modules.get(module);
this.applyMiddlewares(server, components, opaqueTokens);
}
public reflectMiddlewaresTokens(instance: NestGateway): any[] {
const prototype = Object.getPrototypeOf(instance);
return Reflect.getMetadata(GATEWAY_MIDDLEWARES, prototype.constructor) || [];
}
public applyMiddlewares(server, components: Map<string, InstanceWrapper<Injectable>>, tokens: any[]) {
const adapter = this.config.getIoAdapter();
iterate(tokens).map(token => this.bindMiddleware(token.name, components))
.filter(middleware => !isNil(middleware))
.forEach(middleware => adapter.bindMiddleware(server, middleware));
}
public bindMiddleware(token: string, components: Map<string, InstanceWrapper<Injectable>>) {
if (!components.has(token)) {
throw new RuntimeException();
}
const { instance } = components.get(token);
if (!this.isGatewayMiddleware(instance)) return null;
const middleware = instance.resolve();
return isFunction(middleware) ? middleware.bind(instance) : null;
}
public isGatewayMiddleware(middleware: object): middleware is GatewayMiddleware {
return !isUndefined((middleware as GatewayMiddleware).resolve);
}
}