mirror of
https://github.com/nestjs/nest.git
synced 2026-02-21 23:11:44 +00:00
feature: more typings, refactor
This commit is contained in:
@@ -26,7 +26,6 @@ export const GUARDS_METADATA = '__guards__';
|
||||
export const RENDER_METADATA = '__renderTemplate__';
|
||||
export const INTERCEPTORS_METADATA = '__interceptors__';
|
||||
export const HTTP_CODE_METADATA = '__httpCode__';
|
||||
export const GATEWAY_MIDDLEWARES = '__gatewayMiddleware';
|
||||
export const MODULE_PATH = '__module_path__';
|
||||
export const HEADERS_METADATA = '__headers__';
|
||||
export const REDIRECT_METADATA = '__redirect__';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Binds parameters decorators to the particular method
|
||||
* Binds parameter decorators to the method
|
||||
* Useful when the language doesn't provide a 'Parameter Decorators' feature (vanilla JavaScript)
|
||||
* @param {} ...decorators
|
||||
*/
|
||||
|
||||
@@ -2,7 +2,7 @@ import { FILTER_CATCH_EXCEPTIONS } from '../../constants';
|
||||
import { Type } from '../../interfaces';
|
||||
|
||||
/**
|
||||
* Defines the Exceptions Filter. Takes set of exception types as an argument which has to be caught by this Filter.
|
||||
* Defines an exception filter. Takes set of exception types as arguments which have to be caught by this filter.
|
||||
* The class should implement the `ExceptionFilter` interface.
|
||||
*/
|
||||
export function Catch(...exceptions: Type<any>[]): ClassDecorator {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as deprecate from 'deprecate';
|
||||
import * as uuid from 'uuid/v4';
|
||||
import { Type } from './../../interfaces/type.interface';
|
||||
|
||||
/**
|
||||
* Defines the injectable class. This class can inject dependencies through constructor.
|
||||
@@ -65,7 +66,7 @@ export function Interceptor(): ClassDecorator {
|
||||
return (target: object) => {};
|
||||
}
|
||||
|
||||
export function mixin(mixinClass) {
|
||||
export function mixin(mixinClass: Type<any>) {
|
||||
Object.defineProperty(mixinClass, 'name', {
|
||||
value: uuid(),
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { isUndefined } from '../../utils/shared.utils';
|
||||
import { PATH_METADATA } from '../../constants';
|
||||
import { isUndefined } from '../../utils/shared.utils';
|
||||
|
||||
/**
|
||||
* Defines the Controller. The controller can inject dependencies through constructor.
|
||||
* Defines the controller. Controller can inject dependencies through constructor.
|
||||
* Those dependencies have to belong to the same module.
|
||||
*/
|
||||
export function Controller(prefix?: string): ClassDecorator {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { PARAMTYPES_METADATA } from '../../constants';
|
||||
|
||||
export function flatten(arr: any[]) {
|
||||
export function flatten<T extends any[] = any, R extends any[] = any>(
|
||||
arr: T,
|
||||
): R {
|
||||
const flat = [].concat(...arr);
|
||||
return flat.some(Array.isArray) ? flatten(flat) : flat;
|
||||
return (flat.some(Array.isArray) ? flatten(flat) : flat) as R;
|
||||
}
|
||||
|
||||
export const Dependencies = (...dependencies: any[]): ClassDecorator => {
|
||||
|
||||
@@ -5,9 +5,12 @@ import { isFunction } from '../../utils/shared.utils';
|
||||
import { validateEach } from '../../utils/validate-each.util';
|
||||
|
||||
const defineFiltersMetadata = (...filters: (Function | ExceptionFilter)[]) => {
|
||||
return (target: any, key?, descriptor?) => {
|
||||
const isFilterValid = filter =>
|
||||
filter && (isFunction(filter) || isFunction(filter.catch));
|
||||
return (target: any, key?: string, descriptor?: any) => {
|
||||
const isFilterValid = <T extends Function | Record<string, any>>(
|
||||
filter: T,
|
||||
) =>
|
||||
filter &&
|
||||
(isFunction(filter) || isFunction((filter as Record<string, any>).catch));
|
||||
|
||||
if (descriptor) {
|
||||
validateEach(
|
||||
@@ -31,12 +34,12 @@ const defineFiltersMetadata = (...filters: (Function | ExceptionFilter)[]) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Setups exception filters to the chosen context.
|
||||
* Bounds exception filters to the chosen context.
|
||||
* When the `@UseFilters()` is used on the controller level:
|
||||
* - Exception Filter will be set up to every handler (every method)
|
||||
*
|
||||
* When the `@UseFilters()` is used on the handle level:
|
||||
* - Exception Filter will be set up only to specified method
|
||||
* - Exception Filter will be set up only to the specified method
|
||||
*
|
||||
* @param {ExceptionFilter[]} ...filters
|
||||
*/
|
||||
|
||||
@@ -6,7 +6,7 @@ import { isFunction, isUndefined } from '../../utils/shared.utils';
|
||||
|
||||
/**
|
||||
* Injects provider which has to be available in the current injector (module) scope.
|
||||
* Providers are recognized by types or tokens.
|
||||
* Providers are recognized by either types or tokens.
|
||||
*/
|
||||
export function Inject<T = any>(token?: T) {
|
||||
return (target: Object, key: string | symbol, index?: number) => {
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
* Assigns the metadata to the class/function under specified `key`.
|
||||
* This metadata can be reflected using `Reflector` class.
|
||||
*/
|
||||
export const ReflectMetadata = <K = any, V = any>(metadataKey: K, metadataValue: V) => (
|
||||
target: object,
|
||||
key?,
|
||||
descriptor?,
|
||||
) => {
|
||||
export const ReflectMetadata = <K = any, V = any>(
|
||||
metadataKey: K,
|
||||
metadataValue: V,
|
||||
) => (target: object, key?: any, descriptor?: any) => {
|
||||
if (descriptor) {
|
||||
Reflect.defineMetadata(metadataKey, metadataValue, descriptor.value);
|
||||
return descriptor;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { GUARDS_METADATA } from '../../constants';
|
||||
import { extendArrayMetadata } from '../../utils/extend-metadata.util';
|
||||
import { validateEach } from '../../utils/validate-each.util';
|
||||
import { isFunction } from '../../utils/shared.utils';
|
||||
import { CanActivate } from '../../interfaces';
|
||||
import { extendArrayMetadata } from '../../utils/extend-metadata.util';
|
||||
import { isFunction } from '../../utils/shared.utils';
|
||||
import { validateEach } from '../../utils/validate-each.util';
|
||||
|
||||
/**
|
||||
* Binds guards to the particular context.
|
||||
@@ -10,14 +10,16 @@ import { CanActivate } from '../../interfaces';
|
||||
* - Guard will be register to each handler (every method)
|
||||
*
|
||||
* When the `@UseGuards()` is used on the handler level:
|
||||
* - Guard will be registered only to specified method
|
||||
* - Guard will be registered only to the specified method
|
||||
*
|
||||
* @param {} ...guards
|
||||
*/
|
||||
export function UseGuards(...guards: (CanActivate | Function)[]) {
|
||||
return (target: any, key?, descriptor?) => {
|
||||
const isValidGuard = guard =>
|
||||
guard && (isFunction(guard) || isFunction(guard.canActivate));
|
||||
return (target: any, key?: string, descriptor?: any) => {
|
||||
const isValidGuard = <T extends Function | Record<string, any>>(guard: T) =>
|
||||
guard &&
|
||||
(isFunction(guard) ||
|
||||
isFunction((guard as Record<string, any>).canActivate));
|
||||
|
||||
if (descriptor) {
|
||||
validateEach(
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { INTERCEPTORS_METADATA } from '../../constants';
|
||||
import { NestInterceptor } from '../../interfaces';
|
||||
import { extendArrayMetadata } from '../../utils/extend-metadata.util';
|
||||
import { isFunction } from '../../utils/shared.utils';
|
||||
import { validateEach } from '../../utils/validate-each.util';
|
||||
import { NestInterceptor } from '../../interfaces';
|
||||
|
||||
/**
|
||||
* Binds interceptors to the particular context.
|
||||
@@ -10,17 +10,20 @@ import { NestInterceptor } from '../../interfaces';
|
||||
* - Interceptor will be register to each handler (every method)
|
||||
*
|
||||
* When the `@UseInterceptors()` is used on the handle level:
|
||||
* - Interceptor will be registered only to specified method
|
||||
* - Interceptor will be registered only to the specified method
|
||||
*
|
||||
* @param {} ...interceptors
|
||||
*/
|
||||
export function UseInterceptors(
|
||||
...interceptors: (NestInterceptor | Function)[],
|
||||
...interceptors: (NestInterceptor | Function)[]
|
||||
) {
|
||||
return (target: any, key?, descriptor?) => {
|
||||
const isValidInterceptor = interceptor =>
|
||||
return (target: any, key?: string, descriptor?: any) => {
|
||||
const isValidInterceptor = <T extends Function | Record<string, any>>(
|
||||
interceptor: T,
|
||||
) =>
|
||||
interceptor &&
|
||||
(isFunction(interceptor) || isFunction(interceptor.intercept));
|
||||
(isFunction(interceptor) ||
|
||||
isFunction((interceptor as Record<string, any>).intercept));
|
||||
|
||||
if (descriptor) {
|
||||
validateEach(
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { PipeTransform } from '../../interfaces/index';
|
||||
import { PIPES_METADATA } from '../../constants';
|
||||
import { PipeTransform } from '../../interfaces/index';
|
||||
import { extendArrayMetadata } from '../../utils/extend-metadata.util';
|
||||
import { validateEach } from '../../utils/validate-each.util';
|
||||
import { isFunction } from '../../utils/shared.utils';
|
||||
import { validateEach } from '../../utils/validate-each.util';
|
||||
|
||||
/**
|
||||
* Binds pipes to the particular context.
|
||||
@@ -10,14 +10,16 @@ import { isFunction } from '../../utils/shared.utils';
|
||||
* - Pipe will be register to each handler (every method)
|
||||
*
|
||||
* When the `@UsePipes()` is used on the handle level:
|
||||
* - Pipe will be registered only to specified method
|
||||
* - Pipe will be registered only to the specified method
|
||||
*
|
||||
* @param {PipeTransform[]} ...pipes
|
||||
*/
|
||||
export function UsePipes(...pipes: (PipeTransform | Function)[]) {
|
||||
return (target: any, key?, descriptor?) => {
|
||||
const isPipeValid = pipe =>
|
||||
pipe && (isFunction(pipe) || isFunction(pipe.transform));
|
||||
return (target: any, key?: string, descriptor?: any) => {
|
||||
const isPipeValid = <T extends Function | Record<string, any>>(pipe: T) =>
|
||||
pipe &&
|
||||
(isFunction(pipe) || isFunction((pipe as Record<string, any>).transform));
|
||||
|
||||
if (descriptor) {
|
||||
extendArrayMetadata(PIPES_METADATA, pipes, descriptor.value);
|
||||
return descriptor;
|
||||
|
||||
@@ -16,7 +16,7 @@ const assignCustomMetadata = (
|
||||
index: number,
|
||||
factory: CustomParamFactory,
|
||||
data?: ParamData,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
) => ({
|
||||
...args,
|
||||
[`${paramtype}${CUSTOM_ROUTE_AGRS_METADATA}:${index}`]: {
|
||||
@@ -37,17 +37,17 @@ export function createParamDecorator(
|
||||
factory: CustomParamFactory,
|
||||
enhancers: ParamDecoratorEnhancer[] = [],
|
||||
): (
|
||||
...dataOrPipes: (Type<PipeTransform> | PipeTransform | any)[],
|
||||
...dataOrPipes: (Type<PipeTransform> | PipeTransform | any)[]
|
||||
) => ParameterDecorator {
|
||||
const paramtype = uuid();
|
||||
return (
|
||||
data?,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator => (target, key, index) => {
|
||||
const args =
|
||||
Reflect.getMetadata(ROUTE_ARGS_METADATA, target.constructor, key) || {};
|
||||
|
||||
const isPipe = pipe =>
|
||||
const isPipe = (pipe: any) =>
|
||||
pipe &&
|
||||
((isFunction(pipe) && pipe.prototype) || isFunction(pipe.transform));
|
||||
|
||||
@@ -81,7 +81,7 @@ export function createRouteParamDecorator(
|
||||
factory: CustomParamFactory,
|
||||
): (
|
||||
data?: any,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
) => ParameterDecorator {
|
||||
deprecate(
|
||||
'The "createRouteParamDecorator" function is deprecated and will be removed within next major release. Use "createParamDecorator" instead.',
|
||||
|
||||
@@ -17,7 +17,7 @@ const assignMetadata = (
|
||||
paramtype: RouteParamtypes,
|
||||
index: number,
|
||||
data?: ParamData,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
) => ({
|
||||
...args,
|
||||
[`${paramtype}:${index}`]: {
|
||||
@@ -41,8 +41,8 @@ const createRouteParamDecorator = (paramtype: RouteParamtypes) => {
|
||||
};
|
||||
|
||||
const createPipesRouteParamDecorator = (paramtype: RouteParamtypes) => (
|
||||
data?,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
data?: any,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator => (target, key, index) => {
|
||||
const args =
|
||||
Reflect.getMetadata(ROUTE_ARGS_METADATA, target.constructor, key) || {};
|
||||
@@ -70,9 +70,9 @@ export const Next: () => ParameterDecorator = createRouteParamDecorator(
|
||||
export const Session: () => ParameterDecorator = createRouteParamDecorator(
|
||||
RouteParamtypes.SESSION,
|
||||
);
|
||||
export const UploadedFile: (fileKey?: string) => ParameterDecorator = createRouteParamDecorator(
|
||||
RouteParamtypes.FILE,
|
||||
);
|
||||
export const UploadedFile: (
|
||||
fileKey?: string,
|
||||
) => ParameterDecorator = createRouteParamDecorator(RouteParamtypes.FILE);
|
||||
export const UploadedFiles: () => ParameterDecorator = createRouteParamDecorator(
|
||||
RouteParamtypes.FILES,
|
||||
);
|
||||
@@ -80,48 +80,54 @@ export const Headers: (
|
||||
property?: string,
|
||||
) => ParameterDecorator = createRouteParamDecorator(RouteParamtypes.HEADERS);
|
||||
|
||||
export function Query();
|
||||
export function Query(...pipes: (Type<PipeTransform> | PipeTransform)[]);
|
||||
export function Query(): ParameterDecorator;
|
||||
export function Query(
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator;
|
||||
export function Query(
|
||||
property: string,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
);
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator;
|
||||
export function Query(
|
||||
property?: string | (Type<PipeTransform> | PipeTransform),
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
) {
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator {
|
||||
return createPipesRouteParamDecorator(RouteParamtypes.QUERY)(
|
||||
property,
|
||||
...pipes,
|
||||
);
|
||||
}
|
||||
|
||||
export function Body();
|
||||
export function Body(...pipes: (Type<PipeTransform> | PipeTransform)[]);
|
||||
export function Body(): ParameterDecorator;
|
||||
export function Body(
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator;
|
||||
export function Body(
|
||||
property: string,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
);
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator;
|
||||
export function Body(
|
||||
property?: string | (Type<PipeTransform> | PipeTransform),
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
) {
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator {
|
||||
return createPipesRouteParamDecorator(RouteParamtypes.BODY)(
|
||||
property,
|
||||
...pipes,
|
||||
);
|
||||
}
|
||||
|
||||
export function Param();
|
||||
export function Param(...pipes: (Type<PipeTransform> | PipeTransform)[]);
|
||||
export function Param(): ParameterDecorator;
|
||||
export function Param(
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator;
|
||||
export function Param(
|
||||
property: string,
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
);
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator;
|
||||
export function Param(
|
||||
property?: string | (Type<PipeTransform> | PipeTransform),
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[],
|
||||
) {
|
||||
...pipes: (Type<PipeTransform> | PipeTransform)[]
|
||||
): ParameterDecorator {
|
||||
return createPipesRouteParamDecorator(RouteParamtypes.PARAM)(
|
||||
property,
|
||||
...pipes,
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
export const InvalidModuleConfigMessage = (property: string) =>
|
||||
`Invalid property '${property}' in @Module() decorator.`;
|
||||
export const INVALID_MODULE_CONFIG_MESSAGE = (
|
||||
text: TemplateStringsArray,
|
||||
property: string,
|
||||
) => `Invalid property '${property}' in the @Module() decorator.`;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { InvalidModuleConfigMessage } from './constants';
|
||||
import { INVALID_MODULE_CONFIG_MESSAGE } from './constants';
|
||||
|
||||
export class InvalidModuleConfigException extends Error {
|
||||
constructor(property: string) {
|
||||
super(InvalidModuleConfigMessage(property));
|
||||
super(INVALID_MODULE_CONFIG_MESSAGE`${property}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GLOBAL_MODULE_METADATA } from '../../constants';
|
||||
|
||||
/**
|
||||
* Makes the module global-scoped.
|
||||
* Once imported will be available for all existing modules.
|
||||
|
||||
@@ -13,8 +13,10 @@ const metadataKeys = [
|
||||
];
|
||||
|
||||
const validateKeys = (keys: string[]) => {
|
||||
const isKeyInvalid = key => metadataKeys.findIndex(k => k === key) < 0;
|
||||
const validateKey = key => {
|
||||
const isKeyInvalid = (key: string) =>
|
||||
metadataKeys.findIndex(k => k === key) < 0;
|
||||
|
||||
const validateKey = (key: string) => {
|
||||
if (!isKeyInvalid(key)) {
|
||||
return;
|
||||
}
|
||||
@@ -42,7 +44,7 @@ export function Module(metadata: ModuleMetadata): ClassDecorator {
|
||||
return (target: object) => {
|
||||
for (const property in metadata) {
|
||||
if (metadata.hasOwnProperty(property)) {
|
||||
Reflect.defineMetadata(property, metadata[property], target);
|
||||
Reflect.defineMetadata(property, (metadata as any)[property], target);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { SHARED_MODULE_METADATA } from '../../constants';
|
||||
|
||||
/**
|
||||
* Makes the module single-scoped (not singleton).
|
||||
* In this case, Nest will always create a new instance of this particular module when it's imported by another one.
|
||||
@@ -7,7 +8,7 @@ export function SingleScope(): ClassDecorator {
|
||||
return (target: any) => {
|
||||
const Metatype = target as FunctionConstructor;
|
||||
const Type = class extends Metatype {
|
||||
constructor(...args) {
|
||||
constructor(...args: any[]) {
|
||||
super(...args);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as multer from 'multer';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Optional } from '../../decorators';
|
||||
import { mixin } from '../../decorators/core/component.decorator';
|
||||
import { ExecutionContext } from '../../interfaces';
|
||||
import { ExecutionContext, Type } from '../../interfaces';
|
||||
import {
|
||||
MulterField,
|
||||
MulterOptions,
|
||||
@@ -17,7 +17,7 @@ type MulterInstance = any;
|
||||
export function FileFieldsInterceptor(
|
||||
uploadFields: MulterField[],
|
||||
localOptions?: MulterOptions,
|
||||
) {
|
||||
): Type<NestInterceptor> {
|
||||
class MixinInterceptor implements NestInterceptor {
|
||||
readonly upload: MulterInstance;
|
||||
|
||||
@@ -55,5 +55,5 @@ export function FileFieldsInterceptor(
|
||||
}
|
||||
}
|
||||
const Interceptor = mixin(MixinInterceptor);
|
||||
return Interceptor;
|
||||
return Interceptor as Type<NestInterceptor>;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as multer from 'multer';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Optional } from '../../decorators';
|
||||
import { mixin } from '../../decorators/core/component.decorator';
|
||||
import { ExecutionContext } from '../../interfaces';
|
||||
import { ExecutionContext, Type } from '../../interfaces';
|
||||
import { MulterOptions } from '../../interfaces/external/multer-options.interface';
|
||||
import { NestInterceptor } from '../../interfaces/features/nest-interceptor.interface';
|
||||
import { MULTER_MODULE_OPTIONS } from '../files.constants';
|
||||
@@ -14,7 +14,7 @@ type MulterInstance = any;
|
||||
export function FileInterceptor(
|
||||
fieldName: string,
|
||||
localOptions?: MulterOptions,
|
||||
) {
|
||||
): Type<NestInterceptor> {
|
||||
class MixinInterceptor implements NestInterceptor {
|
||||
readonly upload: MulterInstance;
|
||||
|
||||
@@ -52,5 +52,5 @@ export function FileInterceptor(
|
||||
}
|
||||
}
|
||||
const Interceptor = mixin(MixinInterceptor);
|
||||
return Interceptor;
|
||||
return Interceptor as Type<NestInterceptor>;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as multer from 'multer';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Optional } from '../../decorators';
|
||||
import { mixin } from '../../decorators/core/component.decorator';
|
||||
import { ExecutionContext } from '../../interfaces';
|
||||
import { ExecutionContext, Type } from '../../interfaces';
|
||||
import { MulterOptions } from '../../interfaces/external/multer-options.interface';
|
||||
import { NestInterceptor } from '../../interfaces/features/nest-interceptor.interface';
|
||||
import { MULTER_MODULE_OPTIONS } from '../files.constants';
|
||||
@@ -15,7 +15,7 @@ export function FilesInterceptor(
|
||||
fieldName: string,
|
||||
maxCount?: number,
|
||||
localOptions?: MulterOptions,
|
||||
) {
|
||||
): Type<NestInterceptor> {
|
||||
class MixinInterceptor implements NestInterceptor {
|
||||
readonly upload: MulterInstance;
|
||||
|
||||
@@ -53,5 +53,5 @@ export function FilesInterceptor(
|
||||
}
|
||||
}
|
||||
const Interceptor = mixin(MixinInterceptor);
|
||||
return Interceptor;
|
||||
return Interceptor as Type<NestInterceptor>;
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ export class HttpService {
|
||||
|
||||
post<T = any>(
|
||||
url: string,
|
||||
data?,
|
||||
data?: any,
|
||||
config?: AxiosRequestConfig,
|
||||
): Observable<AxiosResponse<T>> {
|
||||
return defer(() => this.instance.post(url, data, config));
|
||||
@@ -44,7 +44,7 @@ export class HttpService {
|
||||
|
||||
put<T = any>(
|
||||
url: string,
|
||||
data?,
|
||||
data?: any,
|
||||
config?: AxiosRequestConfig,
|
||||
): Observable<AxiosResponse<T>> {
|
||||
return defer(() => this.instance.put(url, data, config));
|
||||
@@ -52,7 +52,7 @@ export class HttpService {
|
||||
|
||||
patch<T = any>(
|
||||
url: string,
|
||||
data?,
|
||||
data?: any,
|
||||
config?: AxiosRequestConfig,
|
||||
): Observable<AxiosResponse<T>> {
|
||||
return defer(() => this.instance.patch(url, data, config));
|
||||
|
||||
@@ -21,7 +21,6 @@ export {
|
||||
ExecutionContext,
|
||||
ForwardReference,
|
||||
HttpServer,
|
||||
HttpServerFactory,
|
||||
INestApplication,
|
||||
INestApplicationContext,
|
||||
INestExpressApplication,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ArgumentsHost } from '../features/arguments-host.interface';
|
||||
|
||||
export interface ExceptionFilter<T = any> {
|
||||
catch(exception: T, host: ArgumentsHost);
|
||||
catch(exception: T, host: ArgumentsHost): any;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ArgumentsHost } from '../features/arguments-host.interface';
|
||||
|
||||
export interface WsExceptionFilter<T = any> {
|
||||
catch(exception: T, host: ArgumentsHost);
|
||||
}
|
||||
catch(exception: T, host: ArgumentsHost): any;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export interface MulterOptions {
|
||||
preservePath?: boolean;
|
||||
};
|
||||
fileFilter?(
|
||||
req,
|
||||
req: any,
|
||||
file: {
|
||||
/** Field name specified in the form */
|
||||
fieldname: string;
|
||||
@@ -58,4 +58,4 @@ export interface MulterField {
|
||||
name: string;
|
||||
/** Optional maximum number of files per field to accept. */
|
||||
maxCount?: number;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ export interface ServeStaticOptions {
|
||||
* path the file path that is being sent
|
||||
* stat the stat object of the file that is being sent
|
||||
*/
|
||||
setHeaders?: (res, path: string, stat: any) => any;
|
||||
setHeaders?: (res: any, path: string, stat: any) => any;
|
||||
|
||||
/**
|
||||
* Creates a virtual path prefix
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export interface HttpServerFactory {
|
||||
createServer(Function);
|
||||
}
|
||||
@@ -1,51 +1,59 @@
|
||||
import { IncomingMessage, ServerResponse } from 'http';
|
||||
import { RequestMethod } from '../../enums';
|
||||
|
||||
export type ErrorHandler = (
|
||||
export type ErrorHandler<TRequest = any, TResponse = any> = (
|
||||
error: any,
|
||||
req: Partial<IncomingMessage>,
|
||||
res: ServerResponse | any,
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next?: Function,
|
||||
) => any;
|
||||
export type RequestHandler = (
|
||||
req: Partial<IncomingMessage>,
|
||||
res: ServerResponse | any,
|
||||
export type RequestHandler<TRequest = any, TResponse = any> = (
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next?: Function,
|
||||
) => any;
|
||||
|
||||
export interface HttpServer {
|
||||
use(handler: RequestHandler | ErrorHandler): any;
|
||||
use(path, handler: RequestHandler | ErrorHandler): any;
|
||||
get(handler: RequestHandler): any;
|
||||
get(path, handler: RequestHandler): any;
|
||||
post(handler: RequestHandler): any;
|
||||
post(path, handler: RequestHandler): any;
|
||||
head(handler: RequestHandler): any;
|
||||
head(path, handler: RequestHandler): any;
|
||||
delete(handler: RequestHandler): any;
|
||||
delete(path, handler: RequestHandler): any;
|
||||
put(handler: RequestHandler): any;
|
||||
put(path, handler: RequestHandler): any;
|
||||
patch(handler: RequestHandler): any;
|
||||
patch(path, handler: RequestHandler): any;
|
||||
options(handler: RequestHandler): any;
|
||||
options(path, handler: RequestHandler): any;
|
||||
listen(port: number | string, callback?: () => void);
|
||||
listen(port: number | string, hostname: string, callback?: () => void);
|
||||
reply(response: any, body: any, statusCode: number);
|
||||
render(response: any, view: string, options: any);
|
||||
setHeader(response: any, name: string, value: string);
|
||||
setErrorHandler?(handler: Function);
|
||||
setNotFoundHandler?(handler: Function);
|
||||
export interface HttpServer<TRequest = any, TResponse = any> {
|
||||
use(
|
||||
handler:
|
||||
| RequestHandler<TRequest, TResponse>
|
||||
| ErrorHandler<TRequest, TResponse>,
|
||||
): any;
|
||||
use(
|
||||
path: string,
|
||||
handler:
|
||||
| RequestHandler<TRequest, TResponse>
|
||||
| ErrorHandler<TRequest, TResponse>,
|
||||
): any;
|
||||
get(handler: RequestHandler<TRequest, TResponse>): any;
|
||||
get(path: string, handler: RequestHandler<TRequest, TResponse>): any;
|
||||
post(handler: RequestHandler<TRequest, TResponse>): any;
|
||||
post(path: string, handler: RequestHandler<TRequest, TResponse>): any;
|
||||
head(handler: RequestHandler<TRequest, TResponse>): any;
|
||||
head(path: string, handler: RequestHandler<TRequest, TResponse>): any;
|
||||
delete(handler: RequestHandler<TRequest, TResponse>): any;
|
||||
delete(path: string, handler: RequestHandler<TRequest, TResponse>): any;
|
||||
put(handler: RequestHandler<TRequest, TResponse>): any;
|
||||
put(path: string, handler: RequestHandler<TRequest, TResponse>): any;
|
||||
patch(handler: RequestHandler<TRequest, TResponse>): any;
|
||||
patch(path: string, handler: RequestHandler<TRequest, TResponse>): any;
|
||||
options(handler: RequestHandler<TRequest, TResponse>): any;
|
||||
options(path: string, handler: RequestHandler<TRequest, TResponse>): any;
|
||||
listen(port: number | string, callback?: () => void): any;
|
||||
listen(port: number | string, hostname: string, callback?: () => void): any;
|
||||
reply(response: any, body: any, statusCode: number): any;
|
||||
render(response: any, view: string, options: any): any;
|
||||
setHeader(response: any, name: string, value: string): any;
|
||||
setErrorHandler?(handler: Function): any;
|
||||
setNotFoundHandler?(handler: Function): any;
|
||||
useStaticAssets?(...args: any[]): this;
|
||||
setBaseViewsDir?(path: string): this;
|
||||
setViewEngine?(engineOrOptions: any): this;
|
||||
createMiddlewareFactory(
|
||||
method: RequestMethod,
|
||||
): (path: string, callback: Function) => any;
|
||||
getRequestMethod?(request): string;
|
||||
getRequestUrl?(request): string;
|
||||
getRequestMethod?(request: TRequest): string;
|
||||
getRequestUrl?(request: TResponse): string;
|
||||
getInstance(): any;
|
||||
getHttpServer(): any;
|
||||
close();
|
||||
close(): any;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ export * from './features/execution-context.interface';
|
||||
export * from './features/nest-interceptor.interface';
|
||||
export * from './features/paramtype.interface';
|
||||
export * from './features/pipe-transform.interface';
|
||||
export * from './http/http-server-factory.interface';
|
||||
export * from './http/http-server.interface';
|
||||
export * from './injectable.interface';
|
||||
export * from './middleware';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export interface CustomTransportStrategy {
|
||||
listen(callback: () => void);
|
||||
close();
|
||||
listen(callback: () => void): any;
|
||||
close(): any;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export interface OnModuleDestroy {
|
||||
onModuleDestroy();
|
||||
onModuleDestroy(): any;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export interface OnModuleInit {
|
||||
onModuleInit();
|
||||
onModuleInit(): any;
|
||||
}
|
||||
|
||||
@@ -27,5 +27,5 @@ export interface INestApplicationContext {
|
||||
* Sets custom logger service
|
||||
* @returns {void}
|
||||
*/
|
||||
useLogger(logger: LoggerService);
|
||||
useLogger(logger: LoggerService): void;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export interface INestExpressApplication {
|
||||
*
|
||||
* @returns {this}
|
||||
*/
|
||||
set(...args): this;
|
||||
set(...args: any[]): this;
|
||||
|
||||
/**
|
||||
* A wrapper function around native `express.engine()` method.
|
||||
@@ -15,7 +15,7 @@ export interface INestExpressApplication {
|
||||
*
|
||||
* @returns {this}
|
||||
*/
|
||||
engine(...args): this;
|
||||
engine(...args: any[]): this;
|
||||
|
||||
/**
|
||||
* A wrapper function around native `express.enable()` method.
|
||||
@@ -23,7 +23,7 @@ export interface INestExpressApplication {
|
||||
*
|
||||
* @returns {this}
|
||||
*/
|
||||
enable(...args): this;
|
||||
enable(...args: any[]): this;
|
||||
|
||||
/**
|
||||
* A wrapper function around native `express.disable()` method.
|
||||
@@ -31,7 +31,7 @@ export interface INestExpressApplication {
|
||||
*
|
||||
* @returns {this}
|
||||
*/
|
||||
disable(...args): this;
|
||||
disable(...args: any[]): this;
|
||||
|
||||
/**
|
||||
* Sets a base directory for public assets.
|
||||
|
||||
@@ -5,7 +5,7 @@ export interface INestFastifyApplication {
|
||||
*
|
||||
* @returns {this}
|
||||
*/
|
||||
register(...args): this;
|
||||
register(...args: any[]): this;
|
||||
|
||||
/**
|
||||
* Sets a base directory for public assets.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { WebSocketAdapter } from './websockets/web-socket-adapter.interface';
|
||||
import { ExceptionFilter } from './exceptions/exception-filter.interface';
|
||||
import { PipeTransform } from './features/pipe-transform.interface';
|
||||
import { NestInterceptor } from './features/nest-interceptor.interface';
|
||||
import { CanActivate } from './features/can-activate.interface';
|
||||
import { NestInterceptor } from './features/nest-interceptor.interface';
|
||||
import { PipeTransform } from './features/pipe-transform.interface';
|
||||
import { INestApplicationContext } from './nest-application-context.interface';
|
||||
import { WebSocketAdapter } from './websockets/web-socket-adapter.interface';
|
||||
|
||||
export interface INestMicroservice extends INestApplicationContext {
|
||||
/**
|
||||
@@ -12,7 +12,7 @@ export interface INestMicroservice extends INestApplicationContext {
|
||||
* @param {Function} callback
|
||||
* @returns {Promise}
|
||||
*/
|
||||
listen(callback: () => void);
|
||||
listen(callback: () => void): any;
|
||||
|
||||
/**
|
||||
* Starts the microservice (can be awaited).
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export interface OnApplicationBootstrap {
|
||||
onApplicationBootstrap();
|
||||
onApplicationBootstrap(): any;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
export interface WebSocketAdapter<T = any> {
|
||||
create(port: number, options?: T);
|
||||
bindClientConnect(server: any, callback: (...args: any[]) => void);
|
||||
bindClientDisconnect?(client: any, callback: (...args: any[]) => void);
|
||||
create(port: number, options?: T): any;
|
||||
bindClientConnect(server: any, callback: (...args: any[]) => void): any;
|
||||
bindClientDisconnect?(client: any, callback: (...args: any[]) => void): any;
|
||||
bindMessageHandlers(
|
||||
client: any,
|
||||
handlers: Array<{
|
||||
@@ -11,6 +11,6 @@ export interface WebSocketAdapter<T = any> {
|
||||
callback: (...args: any[]) => Observable<any> | Promise<any> | any;
|
||||
}>,
|
||||
transform: (data: any) => Observable<any>,
|
||||
);
|
||||
close(server: any);
|
||||
): any;
|
||||
close(server: any): any;
|
||||
}
|
||||
|
||||
@@ -27,12 +27,12 @@ export class ValidationPipe implements PipeTransform<any> {
|
||||
this.validatorOptions = validatorOptions;
|
||||
this.isDetailedOutputDisabled = disableErrorMessages;
|
||||
|
||||
const loadPkg = pkg => loadPackage(pkg, 'ValidationPipe');
|
||||
const loadPkg = (pkg: any) => loadPackage(pkg, 'ValidationPipe');
|
||||
classValidator = loadPkg('class-validator');
|
||||
classTransformer = loadPkg('class-transformer');
|
||||
}
|
||||
|
||||
public async transform(value, metadata: ArgumentMetadata) {
|
||||
public async transform(value: any, metadata: ArgumentMetadata) {
|
||||
const { metatype } = metadata;
|
||||
if (!metatype || !this.toValidate(metadata)) {
|
||||
return value;
|
||||
|
||||
@@ -21,7 +21,8 @@ const REFLECTOR = 'Reflector';
|
||||
@Injectable()
|
||||
export class ClassSerializerInterceptor implements NestInterceptor {
|
||||
constructor(@Inject(REFLECTOR) protected readonly reflector: any) {
|
||||
const loadPkg = pkg => loadPackage(pkg, 'ClassSerializerInterceptor');
|
||||
const loadPkg = (pkg: any) =>
|
||||
loadPackage(pkg, 'ClassSerializerInterceptor');
|
||||
classTransformer = loadPkg('class-transformer');
|
||||
}
|
||||
|
||||
@@ -53,7 +54,7 @@ export class ClassSerializerInterceptor implements NestInterceptor {
|
||||
}
|
||||
|
||||
transformToPlain(
|
||||
plainOrClass,
|
||||
plainOrClass: any,
|
||||
options: ClassTransformOptions,
|
||||
): PlainLiteralObject {
|
||||
return plainOrClass && plainOrClass.constructor !== Object
|
||||
@@ -70,7 +71,9 @@ export class ClassSerializerInterceptor implements NestInterceptor {
|
||||
);
|
||||
}
|
||||
|
||||
private reflectSerializeMetadata(obj): ClassTransformOptions | undefined {
|
||||
private reflectSerializeMetadata(
|
||||
obj: object | Function,
|
||||
): ClassTransformOptions | undefined {
|
||||
return this.reflector.get(CLASS_SERIALIZER_OPTIONS, obj);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,12 @@ import { Injectable, Optional } from '../decorators';
|
||||
import { NestEnvironment } from '../enums/nest-environment.enum';
|
||||
import { isObject } from '../utils/shared.utils';
|
||||
|
||||
declare const process;
|
||||
declare const process: any;
|
||||
|
||||
export interface LoggerService {
|
||||
log(message: any, context?: string);
|
||||
error(message: any, trace?: string, context?: string);
|
||||
warn(message: any, context?: string);
|
||||
log(message: any, context?: string): any;
|
||||
error(message: any, trace?: string, context?: string): any;
|
||||
warn(message: any, context?: string): any;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
|
||||
@@ -7,7 +7,7 @@ export const MergeWithValues = <T extends Constructor<{}>>(data: {
|
||||
}) => {
|
||||
return (Metatype: T): any => {
|
||||
const Type = class extends Metatype {
|
||||
constructor(...args) {
|
||||
constructor(...args: any[]) {
|
||||
super(...args);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -7,9 +7,9 @@ import { RouterMethodFactory } from '../helpers/router-method-factory';
|
||||
|
||||
export class ExpressAdapter implements HttpServer {
|
||||
private readonly routerMethodFactory = new RouterMethodFactory();
|
||||
private httpServer = null;
|
||||
private httpServer: any = null;
|
||||
|
||||
constructor(private readonly instance) {}
|
||||
constructor(private readonly instance: any) {}
|
||||
|
||||
use(...args: any[]) {
|
||||
return this.instance.use(...args);
|
||||
@@ -103,19 +103,19 @@ export class ExpressAdapter implements HttpServer {
|
||||
return this.instance.close();
|
||||
}
|
||||
|
||||
set(...args) {
|
||||
set(...args: any[]) {
|
||||
return this.instance.set(...args);
|
||||
}
|
||||
|
||||
enable(...args) {
|
||||
enable(...args: any[]) {
|
||||
return this.instance.enable(...args);
|
||||
}
|
||||
|
||||
disable(...args) {
|
||||
disable(...args: any[]) {
|
||||
return this.instance.disable(...args);
|
||||
}
|
||||
|
||||
engine(...args) {
|
||||
engine(...args: any[]) {
|
||||
return this.instance.engine(...args);
|
||||
}
|
||||
|
||||
|
||||
@@ -88,11 +88,11 @@ export class FastifyAdapter {
|
||||
return this.instance as T;
|
||||
}
|
||||
|
||||
register(...args) {
|
||||
register(...args: any[]) {
|
||||
return this.instance.register(...args);
|
||||
}
|
||||
|
||||
inject(...args) {
|
||||
inject(...args: any[]) {
|
||||
return this.instance.inject(...args);
|
||||
}
|
||||
|
||||
|
||||
@@ -53,16 +53,24 @@ export const UNKNOWN_DEPENDENCIES_MESSAGE = (
|
||||
return message;
|
||||
};
|
||||
|
||||
export const INVALID_MIDDLEWARE_MESSAGE = (text, name: string) =>
|
||||
`The middleware doesn't provide the 'resolve' method (${name})`;
|
||||
export const INVALID_MIDDLEWARE_MESSAGE = (
|
||||
text: TemplateStringsArray,
|
||||
name: string,
|
||||
) => `The middleware doesn't provide the 'resolve' method (${name})`;
|
||||
|
||||
export const INVALID_MODULE_MESSAGE = (text, scope: string) =>
|
||||
export const INVALID_MODULE_MESSAGE = (
|
||||
text: TemplateStringsArray,
|
||||
scope: string,
|
||||
) =>
|
||||
`Nest cannot create the module instance. Often, this is because of a circular dependency between modules. Use forwardRef() to avoid it. (Read more https://docs.nestjs.com/advanced/circular-dependency.) Scope [${scope}]`;
|
||||
|
||||
export const UNKNOWN_EXPORT_MESSAGE = (text, module: string) =>
|
||||
export const UNKNOWN_EXPORT_MESSAGE = (
|
||||
text: TemplateStringsArray,
|
||||
module: string,
|
||||
) =>
|
||||
`Nest cannot export a provider/module that is not a part of the currently processed module (${module}). Please verify whether each exported unit is available in this particular context.`;
|
||||
|
||||
export const INVALID_CLASS_MESSAGE = (text, value: any) =>
|
||||
export const INVALID_CLASS_MESSAGE = (text: TemplateStringsArray, value: any) =>
|
||||
`ModuleRef cannot instantiate class (${value} is not constructable).`;
|
||||
|
||||
export const INVALID_MIDDLEWARE_CONFIGURATION = `Invalid middleware configuration passed inside the module 'configure()' method.`;
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { FILTER_CATCH_EXCEPTIONS } from '@nestjs/common/constants';
|
||||
import { Type } from '@nestjs/common/interfaces';
|
||||
import { ExceptionFilter } from '@nestjs/common/interfaces/exceptions/exception-filter.interface';
|
||||
import { isEmpty, isFunction, isUndefined } from '@nestjs/common/utils/shared.utils';
|
||||
import {
|
||||
isEmpty,
|
||||
isFunction,
|
||||
isUndefined,
|
||||
} from '@nestjs/common/utils/shared.utils';
|
||||
import iterate from 'iterare';
|
||||
import { ContextCreator } from '../helpers/context-creator';
|
||||
import { NestContainer } from '../injector/container';
|
||||
@@ -42,7 +46,9 @@ export class BaseExceptionFilterContext extends ContextCreator {
|
||||
: null;
|
||||
}
|
||||
|
||||
public getInstanceByMetatype(filter): { instance: any } | undefined {
|
||||
public getInstanceByMetatype<T extends Record<string, any>>(
|
||||
filter: T,
|
||||
): { instance: any } | undefined {
|
||||
if (!this.moduleContext) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -54,7 +54,9 @@ export class GuardsContextCreator extends ContextCreator {
|
||||
: null;
|
||||
}
|
||||
|
||||
public getInstanceByMetatype(guard): { instance: any } | undefined {
|
||||
public getInstanceByMetatype<T extends Record<string, any>>(
|
||||
guard: T,
|
||||
): { instance: any } | undefined {
|
||||
if (!this.moduleContext) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ export class ExternalContextCreator {
|
||||
: [];
|
||||
const fnApplyPipes = this.createPipesFn(pipes, paramsOptions);
|
||||
|
||||
const handler = (initialArgs, ...args) => async () => {
|
||||
const handler = (initialArgs: any[], ...args: any[]) => async () => {
|
||||
if (fnApplyPipes) {
|
||||
await fnApplyPipes(initialArgs, ...args);
|
||||
return callback.apply(instance, initialArgs);
|
||||
@@ -158,7 +158,7 @@ export class ExternalContextCreator {
|
||||
return { index, extractValue: customExtractValue, type, data, pipes };
|
||||
}
|
||||
const numericType = Number(type);
|
||||
const extractValue = (...args) =>
|
||||
const extractValue = (...args: any[]) =>
|
||||
paramsFactory.exchangeKeyForValue(numericType, data, args);
|
||||
|
||||
return { index, extractValue, type: numericType, data, pipes };
|
||||
@@ -167,7 +167,7 @@ export class ExternalContextCreator {
|
||||
|
||||
public getCustomFactory(
|
||||
factory: (...args: any[]) => void,
|
||||
data,
|
||||
data: any,
|
||||
): (...args: any[]) => any {
|
||||
return !isUndefined(factory) && isFunction(factory)
|
||||
? (...args: any[]) => factory(data, args)
|
||||
@@ -178,7 +178,7 @@ export class ExternalContextCreator {
|
||||
pipes: any[],
|
||||
paramsOptions: (ParamProperties & { metatype?: any })[],
|
||||
) {
|
||||
const pipesFn = async (args, ...gqlArgs) => {
|
||||
const pipesFn = async (args: any[], ...params: any[]) => {
|
||||
await Promise.all(
|
||||
paramsOptions.map(async param => {
|
||||
const {
|
||||
@@ -189,7 +189,7 @@ export class ExternalContextCreator {
|
||||
metatype,
|
||||
pipes: paramPipes,
|
||||
} = param;
|
||||
const value = extractValue(...gqlArgs);
|
||||
const value = extractValue(...params);
|
||||
|
||||
args[index] = await this.getParamValue(
|
||||
value,
|
||||
@@ -204,7 +204,7 @@ export class ExternalContextCreator {
|
||||
|
||||
public async getParamValue<T>(
|
||||
value: T,
|
||||
{ metatype, type, data },
|
||||
{ metatype, type, data }: { metatype: any; type: any; data: any },
|
||||
transforms: Transform<any>[],
|
||||
): Promise<any> {
|
||||
return this.pipesConsumer.apply(
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { RequestMethod } from '@nestjs/common/enums/request-method.enum';
|
||||
|
||||
export const MODULE_INIT_MESSAGE = (text, module: string) =>
|
||||
`${module} dependencies initialized`;
|
||||
export const MODULE_INIT_MESSAGE = (
|
||||
text: TemplateStringsArray,
|
||||
module: string,
|
||||
) => `${module} dependencies initialized`;
|
||||
|
||||
export const ROUTE_MAPPED_MESSAGE = (path: string, method) =>
|
||||
export const ROUTE_MAPPED_MESSAGE = (path: string, method: string | number) =>
|
||||
`Mapped {${path}, ${RequestMethod[method]}} route`;
|
||||
|
||||
export const CONTROLLER_MAPPING_MESSAGE = (name: string, path: string) =>
|
||||
|
||||
@@ -38,12 +38,12 @@ export class ContainerScanner {
|
||||
return (instanceWrapper as InstanceWrapper<any>).instance;
|
||||
}
|
||||
|
||||
private initFlatContainer() {
|
||||
private initFlatContainer(): void {
|
||||
if (this.flatContainer) {
|
||||
return undefined;
|
||||
return;
|
||||
}
|
||||
const modules = this.container.getModules();
|
||||
const initialValue = {
|
||||
const initialValue: any = {
|
||||
providers: [],
|
||||
controllers: [],
|
||||
injectables: [],
|
||||
|
||||
@@ -72,9 +72,9 @@ export class NestContainer {
|
||||
token: string,
|
||||
dynamicModuleMetadata: Partial<DynamicModule>,
|
||||
scope: Type<any>[],
|
||||
) {
|
||||
): void {
|
||||
if (!dynamicModuleMetadata) {
|
||||
return undefined;
|
||||
return;
|
||||
}
|
||||
this.dynamicModulesMetadata.set(token, dynamicModuleMetadata);
|
||||
|
||||
@@ -85,7 +85,7 @@ export class NestContainer {
|
||||
|
||||
public addDynamicModules(modules: any[], scope: Type<any>[]) {
|
||||
if (!modules) {
|
||||
return undefined;
|
||||
return;
|
||||
}
|
||||
modules.forEach(module => this.addModule(module, scope));
|
||||
}
|
||||
@@ -159,7 +159,7 @@ export class NestContainer {
|
||||
this.modules.clear();
|
||||
}
|
||||
|
||||
public replace(toReplace, options: any & { scope: any[] | null }) {
|
||||
public replace(toReplace: any, options: any & { scope: any[] | null }) {
|
||||
[...this.modules.values()].forEach(module => {
|
||||
module.replace(toReplace, options);
|
||||
});
|
||||
@@ -177,7 +177,7 @@ export class NestContainer {
|
||||
|
||||
public bindGlobalModuleToModule(module: Module, globalModule: Module) {
|
||||
if (module === globalModule) {
|
||||
return undefined;
|
||||
return;
|
||||
}
|
||||
module.addRelatedModule(globalModule);
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ export class Injector {
|
||||
public loadPrototypeOfInstance<T>(
|
||||
{ metatype, name }: InstanceWrapper<T>,
|
||||
collection: Map<string, InstanceWrapper<T>>,
|
||||
) {
|
||||
): void {
|
||||
if (!collection) {
|
||||
return null;
|
||||
}
|
||||
@@ -152,7 +152,7 @@ export class Injector {
|
||||
if (targetWrapper.isResolved) {
|
||||
return;
|
||||
}
|
||||
const callback = async instances => {
|
||||
const callback = async (instances: any[]) => {
|
||||
const properties = await this.resolveProperties(wrapper, module, inject);
|
||||
const instance = await this.instantiateClass(
|
||||
instances,
|
||||
@@ -169,7 +169,7 @@ export class Injector {
|
||||
wrapper: InstanceWrapper<T>,
|
||||
module: Module,
|
||||
inject: InjectorDependency[],
|
||||
callback: (args) => void,
|
||||
callback: (args: any[]) => void,
|
||||
) {
|
||||
const dependencies = isNil(inject)
|
||||
? this.reflectConstructorParams(wrapper.metatype)
|
||||
@@ -309,8 +309,8 @@ export class Injector {
|
||||
public async lookupComponentInRelatedModules(
|
||||
module: Module,
|
||||
name: any,
|
||||
moduleRegistry = [],
|
||||
) {
|
||||
moduleRegistry: any[] = [],
|
||||
): Promise<any> {
|
||||
let componentRef = null;
|
||||
|
||||
const relatedModules: Set<Module> = module.relatedModules || new Set();
|
||||
@@ -383,7 +383,7 @@ export class Injector {
|
||||
const optionalKeys: string[] =
|
||||
Reflect.getMetadata(OPTIONAL_PROPERTY_DEPS_METADATA, type) || [];
|
||||
|
||||
return properties.map(item => ({
|
||||
return properties.map((item: any) => ({
|
||||
...item,
|
||||
name: item.type,
|
||||
isOptional: optionalKeys.includes(item.key),
|
||||
@@ -393,7 +393,7 @@ export class Injector {
|
||||
public applyProperties<T = any>(
|
||||
instance: T,
|
||||
properties: PropertyDependency[],
|
||||
) {
|
||||
): void {
|
||||
if (!isObject(instance)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Type } from '@nestjs/common';
|
||||
import { NestContainer } from './container';
|
||||
import { InstanceWrapper, NestContainer } from './container';
|
||||
import { ContainerScanner } from './container-scanner';
|
||||
import { Injector } from './injector';
|
||||
import { Module } from './module';
|
||||
@@ -29,7 +29,7 @@ export abstract class ModuleRef {
|
||||
type: Type<T>,
|
||||
module: Module,
|
||||
): Promise<T> {
|
||||
const wrapper = {
|
||||
const wrapper: InstanceWrapper<any> = {
|
||||
name: type.name,
|
||||
metatype: type,
|
||||
instance: undefined,
|
||||
@@ -37,7 +37,7 @@ export abstract class ModuleRef {
|
||||
};
|
||||
return new Promise<T>(async (resolve, reject) => {
|
||||
try {
|
||||
const callback = async instances => {
|
||||
const callback = async (instances: any[]) => {
|
||||
const properties = await this.injector.resolveProperties(
|
||||
wrapper,
|
||||
module,
|
||||
|
||||
@@ -242,19 +242,19 @@ export class Module {
|
||||
return name;
|
||||
}
|
||||
|
||||
public isCustomClass(provider): provider is CustomClass {
|
||||
public isCustomClass(provider: any): provider is CustomClass {
|
||||
return !isUndefined((provider as CustomClass).useClass);
|
||||
}
|
||||
|
||||
public isCustomValue(provider): provider is CustomValue {
|
||||
public isCustomValue(provider: any): provider is CustomValue {
|
||||
return !isUndefined((provider as CustomValue).useValue);
|
||||
}
|
||||
|
||||
public isCustomFactory(provider): provider is CustomFactory {
|
||||
public isCustomFactory(provider: any): provider is CustomFactory {
|
||||
return !isUndefined((provider as CustomFactory).useFactory);
|
||||
}
|
||||
|
||||
public isDynamicModule(exported): exported is DynamicModule {
|
||||
public isDynamicModule(exported: any): exported is DynamicModule {
|
||||
return exported && exported.module;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,9 @@ export class InterceptorsContextCreator extends ContextCreator {
|
||||
: null;
|
||||
}
|
||||
|
||||
public getInstanceByMetatype(metatype): { instance: any } | undefined {
|
||||
public getInstanceByMetatype<T extends Record<string, any> = any>(
|
||||
metatype: T,
|
||||
): { instance: any } | undefined {
|
||||
if (!this.moduleContext) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import iterate from 'iterare';
|
||||
import { Injectable } from '@nestjs/common/interfaces/injectable.interface';
|
||||
import {
|
||||
isConstructor,
|
||||
isFunction,
|
||||
isNil,
|
||||
} from '@nestjs/common/utils/shared.utils';
|
||||
import iterate from 'iterare';
|
||||
|
||||
export class MetadataScanner {
|
||||
public scanFromPrototype<T extends Injectable, R>(
|
||||
instance: T,
|
||||
prototype,
|
||||
prototype: any,
|
||||
callback: (name: string) => R,
|
||||
): R[] {
|
||||
return iterate([...this.getAllFilteredMethodNames(prototype)])
|
||||
@@ -18,7 +18,7 @@ export class MetadataScanner {
|
||||
.toArray();
|
||||
}
|
||||
|
||||
*getAllFilteredMethodNames(prototype): IterableIterator<string> {
|
||||
*getAllFilteredMethodNames(prototype: any): IterableIterator<string> {
|
||||
do {
|
||||
yield* iterate(Object.getOwnPropertyNames(prototype))
|
||||
.filter(prop => {
|
||||
|
||||
@@ -17,7 +17,7 @@ export class MiddlewareBuilder implements MiddlewareConsumer {
|
||||
constructor(private readonly routesMapper: RoutesMapper) {}
|
||||
|
||||
public apply(
|
||||
...middleware: Array<Type<any> | Function | any>,
|
||||
...middleware: Array<Type<any> | Function | any>
|
||||
): MiddlewareConfigProxy {
|
||||
return new MiddlewareBuilder.ConfigProxy(this, flatten(middleware));
|
||||
}
|
||||
@@ -38,11 +38,14 @@ export class MiddlewareBuilder implements MiddlewareConsumer {
|
||||
}
|
||||
|
||||
private static readonly ConfigProxy = class implements MiddlewareConfigProxy {
|
||||
private contextParameters = null;
|
||||
private contextParameters: any = null;
|
||||
private excludedRoutes: RouteInfo[] = [];
|
||||
private readonly includedRoutes: any[];
|
||||
|
||||
constructor(private readonly builder: MiddlewareBuilder, middleware) {
|
||||
constructor(
|
||||
private readonly builder: MiddlewareBuilder,
|
||||
middleware: any[],
|
||||
) {
|
||||
this.includedRoutes = filterMiddleware(middleware);
|
||||
}
|
||||
|
||||
@@ -50,13 +53,13 @@ export class MiddlewareBuilder implements MiddlewareConsumer {
|
||||
return this.excludedRoutes;
|
||||
}
|
||||
|
||||
public with(...args): MiddlewareConfigProxy {
|
||||
public with(...args: any[]): MiddlewareConfigProxy {
|
||||
this.contextParameters = args;
|
||||
return this;
|
||||
}
|
||||
|
||||
public exclude(
|
||||
...routes: Array<string | RouteInfo>,
|
||||
...routes: Array<string | RouteInfo>
|
||||
): MiddlewareConfigProxy {
|
||||
const { routesMapper } = this.builder;
|
||||
this.excludedRoutes = this.mapRoutesToFlatList(
|
||||
@@ -66,7 +69,7 @@ export class MiddlewareBuilder implements MiddlewareConsumer {
|
||||
}
|
||||
|
||||
public forRoutes(
|
||||
...routes: Array<string | Type<any> | RouteInfo>,
|
||||
...routes: Array<string | Type<any> | RouteInfo>
|
||||
): MiddlewareConsumer {
|
||||
const {
|
||||
middlewareCollection,
|
||||
@@ -88,7 +91,7 @@ export class MiddlewareBuilder implements MiddlewareConsumer {
|
||||
return this.builder;
|
||||
}
|
||||
|
||||
private mapRoutesToFlatList(forRoutes): RouteInfo[] {
|
||||
private mapRoutesToFlatList(forRoutes: RouteInfo[][]): RouteInfo[] {
|
||||
return forRoutes.reduce((a, b) => a.concat(b));
|
||||
}
|
||||
|
||||
|
||||
@@ -168,7 +168,13 @@ export class MiddlewareModule {
|
||||
undefined,
|
||||
);
|
||||
const router = applicationRef.createMiddlewareFactory(method);
|
||||
const bindWithProxy = middlewareInstance =>
|
||||
const bindWithProxy = (
|
||||
middlewareInstance: <TRequest, TResponse>(
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => void,
|
||||
) =>
|
||||
this.bindHandlerWithProxy(
|
||||
exceptionsHandler,
|
||||
router,
|
||||
@@ -176,15 +182,18 @@ export class MiddlewareModule {
|
||||
path,
|
||||
);
|
||||
const resolve = instance.resolve();
|
||||
|
||||
const middleware = await resolve;
|
||||
bindWithProxy(middleware);
|
||||
}
|
||||
|
||||
private bindHandlerWithProxy(
|
||||
exceptionsHandler: ExceptionsHandler,
|
||||
router: (...args) => void,
|
||||
middleware: (req, res, next) => void,
|
||||
router: (...args: any[]) => void,
|
||||
middleware: <TRequest, TResponse>(
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => void,
|
||||
path: string,
|
||||
) {
|
||||
const proxy = this.routerProxy.createProxy(middleware, exceptionsHandler);
|
||||
|
||||
@@ -2,20 +2,21 @@ import { Type } from '@nestjs/common/interfaces';
|
||||
import { isFunction } from '@nestjs/common/utils/shared.utils';
|
||||
import * as uuid from 'uuid/v4';
|
||||
|
||||
export const filterMiddleware = middleware => {
|
||||
export const filterMiddleware = <T>(middleware: T[]) => {
|
||||
return []
|
||||
.concat(middleware)
|
||||
.filter(isFunction)
|
||||
.map(mapToClass);
|
||||
};
|
||||
|
||||
export const mapToClass = middleware => {
|
||||
export const mapToClass = <T extends Function | Type<any>>(middleware: T) => {
|
||||
if (isClass(middleware)) {
|
||||
return middleware;
|
||||
}
|
||||
return assignToken(
|
||||
class {
|
||||
resolve = (...args: any[]) => (...params) => middleware(...params);
|
||||
resolve = (...args: any[]) => (...params: any[]) =>
|
||||
(middleware as Function)(...params)
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -24,7 +25,7 @@ export function isClass(middleware: any) {
|
||||
return middleware.toString().substring(0, 5) === 'class';
|
||||
}
|
||||
|
||||
export function assignToken(metatype): Type<any> {
|
||||
export function assignToken(metatype: Type<any>): Type<any> {
|
||||
Object.defineProperty(metatype, 'name', { value: uuid() });
|
||||
return metatype;
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ export class NestApplicationContext implements INestApplicationContext {
|
||||
}
|
||||
}
|
||||
|
||||
protected hasOnModuleDestroyHook(instance): instance is OnModuleDestroy {
|
||||
protected hasOnModuleDestroyHook(instance: any): instance is OnModuleDestroy {
|
||||
return !isUndefined((instance as OnModuleDestroy).onModuleDestroy);
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ export class NestApplication extends NestApplicationContext
|
||||
: null;
|
||||
private readonly socketModule = SocketModule ? new SocketModule() : null;
|
||||
private readonly routesResolver: Resolver;
|
||||
private readonly microservices = [];
|
||||
private readonly microservices: any[] = [];
|
||||
private httpServer: http.Server;
|
||||
private isInitialized = false;
|
||||
|
||||
@@ -181,7 +181,7 @@ export class NestApplication extends NestApplicationContext
|
||||
!!app._router.stack &&
|
||||
isFunction(app._router.stack.filter) &&
|
||||
app._router.stack.some(
|
||||
layer => layer && layer.handle && layer.handle.name === name,
|
||||
(layer: any) => layer && layer.handle && layer.handle.name === name,
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -242,7 +242,7 @@ export class NestApplication extends NestApplicationContext
|
||||
return this;
|
||||
}
|
||||
|
||||
public engine(...args): this {
|
||||
public engine(...args: any[]): this {
|
||||
if (!this.isExpress()) {
|
||||
return this;
|
||||
}
|
||||
@@ -250,7 +250,7 @@ export class NestApplication extends NestApplicationContext
|
||||
return this;
|
||||
}
|
||||
|
||||
public set(...args): this {
|
||||
public set(...args: any[]): this {
|
||||
if (!this.isExpress()) {
|
||||
return this;
|
||||
}
|
||||
@@ -258,7 +258,7 @@ export class NestApplication extends NestApplicationContext
|
||||
return this;
|
||||
}
|
||||
|
||||
public disable(...args): this {
|
||||
public disable(...args: any[]): this {
|
||||
if (!this.isExpress()) {
|
||||
return this;
|
||||
}
|
||||
@@ -266,7 +266,7 @@ export class NestApplication extends NestApplicationContext
|
||||
return this;
|
||||
}
|
||||
|
||||
public enable(...args): this {
|
||||
public enable(...args: any[]): this {
|
||||
if (!this.isExpress()) {
|
||||
return this;
|
||||
}
|
||||
@@ -274,13 +274,13 @@ export class NestApplication extends NestApplicationContext
|
||||
return this;
|
||||
}
|
||||
|
||||
public register(...args): this {
|
||||
public register(...args: any[]): this {
|
||||
const adapter = this.httpAdapter as FastifyAdapter;
|
||||
adapter.register && adapter.register(...args);
|
||||
return this;
|
||||
}
|
||||
|
||||
public inject(...args) {
|
||||
public inject(...args: any[]) {
|
||||
const adapter = this.httpAdapter as FastifyAdapter;
|
||||
return adapter.inject && adapter.inject(...args);
|
||||
}
|
||||
@@ -290,13 +290,16 @@ export class NestApplication extends NestApplicationContext
|
||||
return this;
|
||||
}
|
||||
|
||||
public async listen(port: number | string, callback?: () => void);
|
||||
public async listen(
|
||||
port: number | string,
|
||||
callback?: () => void,
|
||||
): Promise<any>;
|
||||
public async listen(
|
||||
port: number | string,
|
||||
hostname: string,
|
||||
callback?: () => void,
|
||||
);
|
||||
public async listen(port: number | string, ...args) {
|
||||
): Promise<any>;
|
||||
public async listen(port: number | string, ...args: any[]): Promise<any> {
|
||||
!this.isInitialized && (await this.init());
|
||||
|
||||
this.httpServer.listen(port, ...args);
|
||||
@@ -305,7 +308,7 @@ export class NestApplication extends NestApplicationContext
|
||||
|
||||
public listenAsync(port: number | string, hostname?: string): Promise<any> {
|
||||
return new Promise(resolve => {
|
||||
const server = this.listen(port, hostname, () => resolve(server));
|
||||
const server: any = this.listen(port, hostname, () => resolve(server));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -353,7 +356,7 @@ export class NestApplication extends NestApplicationContext
|
||||
}
|
||||
|
||||
public useStaticAssets(options: any): this;
|
||||
public useStaticAssets(path: string, options?: ServeStaticOptions);
|
||||
public useStaticAssets(path: string, options?: ServeStaticOptions): this;
|
||||
public useStaticAssets(
|
||||
pathOrOptions: any,
|
||||
options?: ServeStaticOptions,
|
||||
@@ -378,7 +381,7 @@ export class NestApplication extends NestApplicationContext
|
||||
return loadPackage(name, ctx);
|
||||
}
|
||||
|
||||
private async registerMiddleware(instance) {
|
||||
private async registerMiddleware(instance: any) {
|
||||
await this.middlewareModule.registerMiddleware(
|
||||
this.middlewareContainer,
|
||||
instance,
|
||||
|
||||
@@ -78,7 +78,7 @@ export class NestFactoryStatic {
|
||||
* @returns {Promise}
|
||||
*/
|
||||
public async createMicroservice(
|
||||
module,
|
||||
module: any,
|
||||
options?: NestMicroserviceOptions & MicroserviceOptions,
|
||||
): Promise<INestMicroservice> {
|
||||
const { NestMicroservice } = loadPackage(
|
||||
@@ -104,7 +104,7 @@ export class NestFactoryStatic {
|
||||
* @returns {Promise}
|
||||
*/
|
||||
public async createApplicationContext(
|
||||
module,
|
||||
module: any,
|
||||
options?: NestApplicationContextOptions,
|
||||
): Promise<INestApplicationContext> {
|
||||
const container = new NestContainer();
|
||||
@@ -125,7 +125,7 @@ export class NestFactoryStatic {
|
||||
}
|
||||
|
||||
private async initialize(
|
||||
module,
|
||||
module: any,
|
||||
container: NestContainer,
|
||||
config = new ApplicationConfig(),
|
||||
httpServer: HttpServer = null,
|
||||
@@ -149,7 +149,7 @@ export class NestFactoryStatic {
|
||||
}
|
||||
}
|
||||
|
||||
private createProxy(target) {
|
||||
private createProxy(target: any) {
|
||||
const proxy = this.createExceptionProxy();
|
||||
return new Proxy(target, {
|
||||
get: proxy,
|
||||
@@ -158,7 +158,7 @@ export class NestFactoryStatic {
|
||||
}
|
||||
|
||||
private createExceptionProxy() {
|
||||
return (receiver, prop) => {
|
||||
return (receiver: Record<string, any>, prop: string) => {
|
||||
if (!(prop in receiver)) return;
|
||||
|
||||
if (isFunction(receiver[prop])) {
|
||||
|
||||
@@ -18,7 +18,7 @@ export class PipesConsumer {
|
||||
|
||||
public async applyPipes<TInput = any>(
|
||||
value: TInput,
|
||||
{ metatype, type, data }: { metatype; type?; data? },
|
||||
{ metatype, type, data }: { metatype: any; type?: any; data?: any },
|
||||
transforms: Transform<any>[],
|
||||
) {
|
||||
return transforms.reduce(async (defferedValue, fn) => {
|
||||
|
||||
@@ -52,13 +52,15 @@ export class PipesContextCreator extends ContextCreator {
|
||||
if (isObject) {
|
||||
return pipe;
|
||||
}
|
||||
const instanceWrapper = this.getInstanceByMetatype(pipe);
|
||||
const instanceWrapper = this.getInstanceByMetatype(pipe as Function);
|
||||
return instanceWrapper && instanceWrapper.instance
|
||||
? instanceWrapper.instance
|
||||
: null;
|
||||
}
|
||||
|
||||
public getInstanceByMetatype(metatype): { instance: any } | undefined {
|
||||
public getInstanceByMetatype<T extends { name: string } = any>(
|
||||
metatype: T,
|
||||
): { instance: any } | undefined {
|
||||
if (!this.moduleContext) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -2,5 +2,9 @@ import { Controller } from '@nestjs/common/interfaces/controllers/controller.int
|
||||
import { ExceptionsHandler } from '../../exceptions/exceptions-handler';
|
||||
|
||||
export interface ExceptionsFilter {
|
||||
create(instance: Controller, callback, module: string): ExceptionsHandler;
|
||||
create(
|
||||
instance: Controller,
|
||||
callback: Function,
|
||||
module: string,
|
||||
): ExceptionsHandler;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export interface Resolver {
|
||||
resolve(instance: any, basePath: string);
|
||||
registerNotFoundHandler();
|
||||
registerExceptionHandler();
|
||||
resolve(instance: any, basePath: string): void;
|
||||
registerNotFoundHandler(): void;
|
||||
registerExceptionHandler(): void;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
|
||||
|
||||
export interface IRouteParamsFactory {
|
||||
exchangeKeyForValue(key: RouteParamtypes | string, data, { req, res, next });
|
||||
exchangeKeyForValue<
|
||||
TRequest extends Record<string, any> = any,
|
||||
TResponse = any,
|
||||
TResult = any
|
||||
>(
|
||||
key: RouteParamtypes | string,
|
||||
data: any,
|
||||
{ req, res, next }: { req: TRequest; res: TResponse; next: Function },
|
||||
): TResult;
|
||||
}
|
||||
|
||||
@@ -2,18 +2,22 @@ import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
|
||||
import { IRouteParamsFactory } from './interfaces/route-params-factory.interface';
|
||||
|
||||
export class RouteParamsFactory implements IRouteParamsFactory {
|
||||
public exchangeKeyForValue(
|
||||
public exchangeKeyForValue<
|
||||
TRequest extends Record<string, any> = any,
|
||||
TResponse = any,
|
||||
TResult = any
|
||||
>(
|
||||
key: RouteParamtypes | string,
|
||||
data: string | object | any,
|
||||
{ req, res, next },
|
||||
) {
|
||||
{ req, res, next }: { req: TRequest; res: TResponse; next: Function },
|
||||
): TResult {
|
||||
switch (key) {
|
||||
case RouteParamtypes.NEXT:
|
||||
return next;
|
||||
return next as any;
|
||||
case RouteParamtypes.REQUEST:
|
||||
return req;
|
||||
return req as any;
|
||||
case RouteParamtypes.RESPONSE:
|
||||
return res;
|
||||
return res as any;
|
||||
case RouteParamtypes.BODY:
|
||||
return data && req.body ? req.body[data] : req.body;
|
||||
case RouteParamtypes.PARAM:
|
||||
|
||||
@@ -40,7 +40,11 @@ export interface ParamProperties {
|
||||
type: RouteParamtypes | string;
|
||||
data: ParamData;
|
||||
pipes: PipeTransform[];
|
||||
extractValue: (req, res, next) => any;
|
||||
extractValue: <TRequest, TResponse>(
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => any;
|
||||
}
|
||||
|
||||
export class RouterExecutionContext {
|
||||
@@ -107,12 +111,21 @@ export class RouterExecutionContext {
|
||||
isResponseHandled,
|
||||
httpStatusCode,
|
||||
);
|
||||
const handler = (args, req, res, next) => async () => {
|
||||
const handler = <TRequest, TResponse>(
|
||||
args: any[],
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => async () => {
|
||||
fnApplyPipes && (await fnApplyPipes(args, req, res, next));
|
||||
return callback.apply(instance, args);
|
||||
};
|
||||
|
||||
return async (req, res, next) => {
|
||||
return async <TRequest, TResponse>(
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => {
|
||||
const args = this.contextUtils.createNullArray(argsLength);
|
||||
fnCanActivate && (await fnCanActivate([req, res]));
|
||||
|
||||
@@ -131,11 +144,13 @@ export class RouterExecutionContext {
|
||||
return Reflect.getMetadata(HTTP_CODE_METADATA, callback);
|
||||
}
|
||||
|
||||
public reflectRenderTemplate(callback): string {
|
||||
public reflectRenderTemplate(callback: (...args: any[]) => any): string {
|
||||
return Reflect.getMetadata(RENDER_METADATA, callback);
|
||||
}
|
||||
|
||||
public reflectResponseHeaders(callback): CustomHeader[] {
|
||||
public reflectResponseHeaders(
|
||||
callback: (...args: any[]) => any,
|
||||
): CustomHeader[] {
|
||||
return Reflect.getMetadata(HEADERS_METADATA, callback) || [];
|
||||
}
|
||||
|
||||
@@ -158,7 +173,11 @@ export class RouterExecutionContext {
|
||||
return { index, extractValue: customExtractValue, type, data, pipes };
|
||||
}
|
||||
const numericType = Number(type);
|
||||
const extractValue = (req, res, next) =>
|
||||
const extractValue = <TRequest, TResponse>(
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) =>
|
||||
this.paramsFactory.exchangeKeyForValue(numericType, data, {
|
||||
req,
|
||||
res,
|
||||
@@ -170,7 +189,7 @@ export class RouterExecutionContext {
|
||||
|
||||
public getCustomFactory(
|
||||
factory: (...args: any[]) => void,
|
||||
data,
|
||||
data: any,
|
||||
): (...args: any[]) => any {
|
||||
return !isUndefined(factory) && isFunction(factory)
|
||||
? (req, res, next) => factory(data, req)
|
||||
@@ -179,7 +198,11 @@ export class RouterExecutionContext {
|
||||
|
||||
public async getParamValue<T>(
|
||||
value: T,
|
||||
{ metatype, type, data },
|
||||
{
|
||||
metatype,
|
||||
type,
|
||||
data,
|
||||
}: { metatype: any; type: RouteParamtypes; data: any },
|
||||
transforms: Transform<any>[],
|
||||
): Promise<any> {
|
||||
if (
|
||||
@@ -190,7 +213,7 @@ export class RouterExecutionContext {
|
||||
) {
|
||||
return this.pipesConsumer.apply(
|
||||
value,
|
||||
{ metatype, type, data },
|
||||
{ metatype, type, data } as any,
|
||||
transforms,
|
||||
);
|
||||
}
|
||||
@@ -220,7 +243,12 @@ export class RouterExecutionContext {
|
||||
pipes: any[],
|
||||
paramsOptions: (ParamProperties & { metatype?: any })[],
|
||||
) {
|
||||
const pipesFn = async (args, req, res, next) => {
|
||||
const pipesFn = async <TRequest, TResponse>(
|
||||
args: any[],
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => {
|
||||
await Promise.all(
|
||||
paramsOptions.map(async param => {
|
||||
const {
|
||||
@@ -235,7 +263,7 @@ export class RouterExecutionContext {
|
||||
|
||||
args[index] = await this.getParamValue(
|
||||
value,
|
||||
{ metatype, type, data },
|
||||
{ metatype, type, data } as any,
|
||||
pipes.concat(paramPipes),
|
||||
);
|
||||
}),
|
||||
@@ -245,7 +273,7 @@ export class RouterExecutionContext {
|
||||
}
|
||||
|
||||
public createHandleResponseFn(
|
||||
callback,
|
||||
callback: (...args: any[]) => any,
|
||||
isResponseHandled: boolean,
|
||||
httpStatusCode: number,
|
||||
) {
|
||||
@@ -254,13 +282,13 @@ export class RouterExecutionContext {
|
||||
const hasCustomHeaders = !isEmpty(responseHeaders);
|
||||
|
||||
if (renderTemplate) {
|
||||
return async (result, res) => {
|
||||
return async <TResult, TResponse>(result: TResult, res: TResponse) => {
|
||||
hasCustomHeaders &&
|
||||
this.responseController.setHeaders(res, responseHeaders);
|
||||
await this.responseController.render(result, res, renderTemplate);
|
||||
};
|
||||
}
|
||||
return async (result, res) => {
|
||||
return async <TResult, TResponse>(result: TResult, res: TResponse) => {
|
||||
hasCustomHeaders &&
|
||||
this.responseController.setHeaders(res, responseHeaders);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { HttpServer } from '@nestjs/common';
|
||||
import { METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
|
||||
import { RequestMethod } from '@nestjs/common/enums/request-method.enum';
|
||||
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
|
||||
@@ -56,7 +57,7 @@ export class RouterExplorer {
|
||||
instance: Controller,
|
||||
metatype: Type<Controller>,
|
||||
module: string,
|
||||
appInstance,
|
||||
appInstance: any,
|
||||
basePath: string,
|
||||
) {
|
||||
const routerPaths = this.scanForPaths(instance);
|
||||
@@ -85,7 +86,10 @@ export class RouterExplorer {
|
||||
return validatePath(path);
|
||||
}
|
||||
|
||||
public scanForPaths(instance: Controller, prototype?): RoutePathProperties[] {
|
||||
public scanForPaths(
|
||||
instance: Controller,
|
||||
prototype?: any,
|
||||
): RoutePathProperties[] {
|
||||
const instancePrototype = isUndefined(prototype)
|
||||
? Object.getPrototypeOf(instance)
|
||||
: prototype;
|
||||
@@ -99,7 +103,7 @@ export class RouterExplorer {
|
||||
|
||||
public exploreMethodMetadata(
|
||||
instance: Controller,
|
||||
instancePrototype,
|
||||
instancePrototype: any,
|
||||
methodName: string,
|
||||
): RoutePathProperties {
|
||||
const targetCallback = instancePrototype[methodName];
|
||||
@@ -119,8 +123,8 @@ export class RouterExplorer {
|
||||
};
|
||||
}
|
||||
|
||||
public applyPathsToRouterProxy(
|
||||
router,
|
||||
public applyPathsToRouterProxy<T extends HttpServer>(
|
||||
router: T,
|
||||
routePaths: RoutePathProperties[],
|
||||
instance: Controller,
|
||||
module: string,
|
||||
@@ -139,8 +143,8 @@ export class RouterExplorer {
|
||||
});
|
||||
}
|
||||
|
||||
private applyCallbackToRouter(
|
||||
router,
|
||||
private applyCallbackToRouter<T extends HttpServer>(
|
||||
router: T,
|
||||
pathProperties: RoutePathProperties,
|
||||
instance: Controller,
|
||||
module: string,
|
||||
@@ -158,7 +162,7 @@ export class RouterExplorer {
|
||||
module,
|
||||
requestMethod,
|
||||
);
|
||||
const stripSlash = str =>
|
||||
const stripSlash = (str: string) =>
|
||||
str[str.length - 1] === '/' ? str.slice(0, str.length - 1) : str;
|
||||
const fullPath = stripSlash(basePath) + path;
|
||||
routerMethod(stripSlash(fullPath) || '/', proxy);
|
||||
@@ -169,7 +173,7 @@ export class RouterExplorer {
|
||||
callback: RouterProxyCallback,
|
||||
methodName: string,
|
||||
module: string,
|
||||
requestMethod,
|
||||
requestMethod: RequestMethod,
|
||||
) {
|
||||
const executionContext = this.executionContextCreator.create(
|
||||
instance,
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
import { ExceptionsHandler } from '../exceptions/exceptions-handler';
|
||||
import { ExecutionContextHost } from '../helpers/execution-context.host';
|
||||
|
||||
export type RouterProxyCallback = (req?, res?, next?) => void;
|
||||
export type RouterProxyCallback = <TRequest, TResponse>(
|
||||
req?: TRequest,
|
||||
res?: TResponse,
|
||||
next?: Function,
|
||||
) => void;
|
||||
|
||||
export class RouterProxy {
|
||||
public createProxy(
|
||||
targetCallback: RouterProxyCallback,
|
||||
exceptionsHandler: ExceptionsHandler,
|
||||
) {
|
||||
return async (req, res, next) => {
|
||||
return async <TRequest, TResponse>(
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => {
|
||||
try {
|
||||
await targetCallback(req, res, next);
|
||||
} catch (e) {
|
||||
@@ -19,10 +27,20 @@ export class RouterProxy {
|
||||
}
|
||||
|
||||
public createExceptionLayerProxy(
|
||||
targetCallback: (err, req, res, next) => void,
|
||||
targetCallback: <TError, TRequest, TResponse>(
|
||||
err: TError,
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => void,
|
||||
exceptionsHandler: ExceptionsHandler,
|
||||
) {
|
||||
return async (err, req, res, next) => {
|
||||
return async <TError, TRequest, TResponse>(
|
||||
err: TError,
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => {
|
||||
try {
|
||||
await targetCallback(err, req, res, next);
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { RequestMethod, HttpStatus, HttpServer } from '@nestjs/common';
|
||||
import { HttpServer, HttpStatus, RequestMethod } from '@nestjs/common';
|
||||
import { isFunction } from '@nestjs/common/utils/shared.utils';
|
||||
|
||||
export interface CustomHeader {
|
||||
@@ -9,17 +9,25 @@ export interface CustomHeader {
|
||||
export class RouterResponseController {
|
||||
constructor(private readonly applicationRef: HttpServer) {}
|
||||
|
||||
public async apply(resultOrDeffered, response, httpStatusCode: number) {
|
||||
public async apply<TInput = any, TResponse = any>(
|
||||
resultOrDeffered: TInput,
|
||||
response: TResponse,
|
||||
httpStatusCode: number,
|
||||
) {
|
||||
const result = await this.transformToResult(resultOrDeffered);
|
||||
return this.applicationRef.reply(response, result, httpStatusCode);
|
||||
}
|
||||
|
||||
public async render(resultOrDeffered, response, template: string) {
|
||||
public async render<TInput = any, TResponse = any>(
|
||||
resultOrDeffered: TInput,
|
||||
response: TResponse,
|
||||
template: string,
|
||||
) {
|
||||
const result = await this.transformToResult(resultOrDeffered);
|
||||
this.applicationRef.render(response, template, result);
|
||||
}
|
||||
|
||||
public async transformToResult(resultOrDeffered) {
|
||||
public async transformToResult(resultOrDeffered: any) {
|
||||
if (resultOrDeffered && isFunction(resultOrDeffered.subscribe)) {
|
||||
return resultOrDeffered.toPromise();
|
||||
}
|
||||
@@ -35,7 +43,10 @@ export class RouterResponseController {
|
||||
}
|
||||
}
|
||||
|
||||
public setHeaders(response, headers: CustomHeader[]) {
|
||||
public setHeaders<TResponse = any>(
|
||||
response: TResponse,
|
||||
headers: CustomHeader[],
|
||||
) {
|
||||
headers.forEach(({ name, value }) =>
|
||||
this.applicationRef.setHeader(response, name, value),
|
||||
);
|
||||
|
||||
@@ -36,7 +36,10 @@ export class RoutesResolver implements Resolver {
|
||||
);
|
||||
}
|
||||
|
||||
public resolve(appInstance, basePath: string) {
|
||||
public resolve<TApplication extends HttpServer>(
|
||||
appInstance: TApplication,
|
||||
basePath: string,
|
||||
) {
|
||||
const modules = this.container.getModules();
|
||||
modules.forEach(({ controllers, metatype }, moduleName) => {
|
||||
let path = metatype
|
||||
@@ -70,7 +73,7 @@ export class RoutesResolver implements Resolver {
|
||||
|
||||
public registerNotFoundHandler() {
|
||||
const applicationRef = this.container.getApplicationRef();
|
||||
const callback = (req, res) => {
|
||||
const callback = <TRequest, TResponse>(req: TRequest, res: TResponse) => {
|
||||
const method = applicationRef.getRequestMethod(req);
|
||||
const url = applicationRef.getRequestUrl(req);
|
||||
throw new NotFoundException(`Cannot ${method} ${url}`);
|
||||
@@ -82,7 +85,12 @@ export class RoutesResolver implements Resolver {
|
||||
}
|
||||
|
||||
public registerExceptionHandler() {
|
||||
const callback = (err, req, res, next) => {
|
||||
const callback = <TError, TRequest, TResponse>(
|
||||
err: TError,
|
||||
req: TRequest,
|
||||
res: TResponse,
|
||||
next: Function,
|
||||
) => {
|
||||
throw this.mapExternalException(err);
|
||||
};
|
||||
const handler = this.routerExceptionsFilter.create(
|
||||
|
||||
@@ -210,11 +210,13 @@ export class DependenciesScanner {
|
||||
component.prototype,
|
||||
method => Reflect.getMetadata(metadataKey, component, method),
|
||||
);
|
||||
const flatten = arr => arr.reduce((a, b) => a.concat(b), []);
|
||||
const paramsInjectables = flatten(paramsMetadata).map(param =>
|
||||
flatten(Object.keys(param).map(k => param[k].pipes)).filter(isFunction),
|
||||
const flatten = (arr: any[]) =>
|
||||
arr.reduce((a: any[], b: any[]) => a.concat(b), []);
|
||||
const paramsInjectables = flatten(paramsMetadata).map(
|
||||
(param: Record<string, any>) =>
|
||||
flatten(Object.keys(param).map(k => param[k].pipes)).filter(isFunction),
|
||||
);
|
||||
flatten(paramsInjectables).forEach(injectable =>
|
||||
flatten(paramsInjectables).forEach((injectable: Type<Injectable>) =>
|
||||
this.insertInjectable(injectable, token),
|
||||
);
|
||||
}
|
||||
@@ -288,8 +290,8 @@ export class DependenciesScanner {
|
||||
);
|
||||
}
|
||||
|
||||
public insertInjectable(component: Type<Injectable>, token: string) {
|
||||
this.container.addInjectable(component, token);
|
||||
public insertInjectable(injectable: Type<Injectable>, token: string) {
|
||||
this.container.addInjectable(injectable, token);
|
||||
}
|
||||
|
||||
public insertExportedProvider(
|
||||
@@ -322,11 +324,12 @@ export class DependenciesScanner {
|
||||
|
||||
public getApplyProvidersMap(): { [type: string]: Function } {
|
||||
return {
|
||||
[APP_INTERCEPTOR]: interceptor =>
|
||||
[APP_INTERCEPTOR]: (interceptor: any) =>
|
||||
this.applicationConfig.addGlobalInterceptor(interceptor),
|
||||
[APP_PIPE]: pipe => this.applicationConfig.addGlobalPipe(pipe),
|
||||
[APP_GUARD]: guard => this.applicationConfig.addGlobalGuard(guard),
|
||||
[APP_FILTER]: filter => this.applicationConfig.addGlobalFilter(filter),
|
||||
[APP_PIPE]: (pipe: any) => this.applicationConfig.addGlobalPipe(pipe),
|
||||
[APP_GUARD]: (guard: any) => this.applicationConfig.addGlobalGuard(guard),
|
||||
[APP_FILTER]: (filter: any) =>
|
||||
this.applicationConfig.addGlobalFilter(filter),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import * as sinon from 'sinon';
|
||||
import { Type } from '@nestjs/common';
|
||||
import { expect } from 'chai';
|
||||
import * as sinon from 'sinon';
|
||||
import {
|
||||
filterMiddleware,
|
||||
mapToClass,
|
||||
isClass,
|
||||
assignToken,
|
||||
filterMiddleware,
|
||||
isClass,
|
||||
mapToClass,
|
||||
} from '../../middleware/utils';
|
||||
|
||||
describe('middleware utils', () => {
|
||||
@@ -33,12 +34,12 @@ describe('middleware utils', () => {
|
||||
expect(metatype).to.not.eql(fnMiddleware);
|
||||
});
|
||||
it('should define `resolve` method', () => {
|
||||
const metatype = mapToClass(fnMiddleware);
|
||||
const metatype = mapToClass(fnMiddleware) as Type<any>;
|
||||
expect(new metatype().resolve).to.exist;
|
||||
});
|
||||
it('should encapsulate function', () => {
|
||||
const spy = sinon.spy();
|
||||
const metatype = mapToClass(spy);
|
||||
const metatype = mapToClass(spy) as Type<any>;
|
||||
new metatype().resolve()();
|
||||
expect(spy.called).to.be.true;
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as sinon from 'sinon';
|
||||
import { expect } from 'chai';
|
||||
import { PipesContextCreator } from '../../pipes/pipes-context-creator';
|
||||
import * as sinon from 'sinon';
|
||||
import { NestContainer } from '../../injector/container';
|
||||
import { PipesContextCreator } from '../../pipes/pipes-context-creator';
|
||||
|
||||
class Pipe {}
|
||||
|
||||
@@ -72,7 +72,9 @@ describe('PipesContextCreator', () => {
|
||||
const instance = { test: true };
|
||||
const module = { injectables: { get: () => instance } };
|
||||
sinon.stub(container.getModules(), 'get').callsFake(() => module);
|
||||
expect(creator.getInstanceByMetatype({})).to.be.eql(instance);
|
||||
expect(creator.getInstanceByMetatype({ name: 'test' })).to.be.eql(
|
||||
instance,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,7 +86,7 @@ export class ClientGrpcProxy extends ClientProxy implements ClientGrpc {
|
||||
call.removeAllListeners();
|
||||
observer.complete();
|
||||
});
|
||||
return () => {
|
||||
return (): any => {
|
||||
if (call.finished) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -176,7 +176,7 @@ export class ClientGrpcProxy extends ClientProxy implements ClientGrpc {
|
||||
);
|
||||
}
|
||||
|
||||
protected publish(partialPacket, callback: (packet) => any) {
|
||||
protected publish(partialPacket: any, callback: (packet: any) => any) {
|
||||
throw new Error(
|
||||
'Method is not supported in gRPC mode. Use ClientGrpc instead (learn more in the documentation).',
|
||||
);
|
||||
|
||||
@@ -85,7 +85,7 @@ export class ClientMqtt extends ClientProxy {
|
||||
);
|
||||
}
|
||||
|
||||
public createResponseCallback(): (channel: string, buffer) => any {
|
||||
public createResponseCallback(): (channel: string, buffer: Buffer) => any {
|
||||
return (channel: string, buffer: Buffer) => {
|
||||
const { err, response, isDisposed, id } = JSON.parse(
|
||||
buffer.toString(),
|
||||
|
||||
@@ -78,10 +78,10 @@ export abstract class ClientProxy {
|
||||
return merge(error$, connect$).pipe(take(1));
|
||||
}
|
||||
|
||||
protected getOptionsProp<T extends { options? }>(
|
||||
protected getOptionsProp<T extends { options?: any }>(
|
||||
obj: ClientOptions['options'],
|
||||
prop: keyof T['options'],
|
||||
defaultValue = undefined,
|
||||
defaultValue: any = undefined,
|
||||
) {
|
||||
return obj ? obj[prop as string] : defaultValue;
|
||||
}
|
||||
|
||||
@@ -89,7 +89,8 @@ export class ClientRedis extends ClientProxy {
|
||||
}
|
||||
|
||||
public getClientOptions(error$: Subject<Error>): Partial<ClientOpts> {
|
||||
const retry_strategy = options => this.createRetryStrategy(options, error$);
|
||||
const retry_strategy = (options: RetryStrategyOptions) =>
|
||||
this.createRetryStrategy(options, error$);
|
||||
return {
|
||||
retry_strategy,
|
||||
};
|
||||
|
||||
@@ -60,7 +60,7 @@ export class ClientRMQ extends ClientProxy {
|
||||
}
|
||||
|
||||
public consumeChannel() {
|
||||
this.channel.addSetup(channel =>
|
||||
this.channel.addSetup((channel: any) =>
|
||||
channel.consume(
|
||||
this.replyQueue,
|
||||
(msg: any) =>
|
||||
@@ -88,7 +88,7 @@ export class ClientRMQ extends ClientProxy {
|
||||
return new Promise(resolve => {
|
||||
this.channel = this.client.createChannel({
|
||||
json: false,
|
||||
setup: channel => this.setupChannel(channel, resolve),
|
||||
setup: (channel: any) => this.setupChannel(channel, resolve),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -130,7 +130,7 @@ export class ClientRMQ extends ClientProxy {
|
||||
): Function {
|
||||
try {
|
||||
const correlationId = randomStringGenerator();
|
||||
const listener = ({ content }) =>
|
||||
const listener = ({ content }: { content: any }) =>
|
||||
this.handleMessage(JSON.parse(content.toString()), callback);
|
||||
|
||||
this.responseEmitter.on(correlationId, listener);
|
||||
|
||||
@@ -57,7 +57,7 @@ export class ClientTCP extends ClientProxy {
|
||||
return this.connection;
|
||||
}
|
||||
|
||||
public handleResponse(buffer: WritePacket & PacketId) {
|
||||
public handleResponse(buffer: WritePacket & PacketId): void {
|
||||
const { err, response, isDisposed, id } = buffer;
|
||||
const callback = this.routingMap.get(id);
|
||||
if (!callback) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { PATTERN_METADATA, PATTERN_HANDLER_METADATA } from '../constants';
|
||||
import { PATTERN_HANDLER_METADATA, PATTERN_METADATA } from '../constants';
|
||||
import { PatternMetadata } from '../interfaces/pattern-metadata.interface';
|
||||
|
||||
/**
|
||||
@@ -7,7 +7,11 @@ import { PatternMetadata } from '../interfaces/pattern-metadata.interface';
|
||||
export const MessagePattern = <T = PatternMetadata | string>(
|
||||
metadata?: T,
|
||||
): MethodDecorator => {
|
||||
return (target, key, descriptor: PropertyDescriptor) => {
|
||||
return (
|
||||
target: any,
|
||||
key: string | symbol,
|
||||
descriptor: PropertyDescriptor,
|
||||
) => {
|
||||
Reflect.defineMetadata(PATTERN_METADATA, metadata, descriptor.value);
|
||||
Reflect.defineMetadata(PATTERN_HANDLER_METADATA, true, descriptor.value);
|
||||
return descriptor;
|
||||
@@ -17,10 +21,14 @@ export const MessagePattern = <T = PatternMetadata | string>(
|
||||
/**
|
||||
* Registers gRPC method handler for specified service.
|
||||
*/
|
||||
export function GrpcMethod(service?: string);
|
||||
export function GrpcMethod(service: string, method?: string);
|
||||
export function GrpcMethod(service: string, method?: string) {
|
||||
return (target, key, descriptor: PropertyDescriptor) => {
|
||||
export function GrpcMethod(service?: string): MethodDecorator;
|
||||
export function GrpcMethod(service: string, method?: string): MethodDecorator;
|
||||
export function GrpcMethod(service: string, method?: string): MethodDecorator {
|
||||
return (
|
||||
target: any,
|
||||
key: string | symbol,
|
||||
descriptor: PropertyDescriptor,
|
||||
) => {
|
||||
const metadata = createMethodMetadata(target, key, service, method);
|
||||
return MessagePattern(metadata)(target, key, descriptor);
|
||||
};
|
||||
@@ -28,7 +36,7 @@ export function GrpcMethod(service: string, method?: string) {
|
||||
|
||||
export function createMethodMetadata(
|
||||
target: any,
|
||||
key: string,
|
||||
key: string | symbol,
|
||||
service: string | undefined,
|
||||
method: string | undefined,
|
||||
) {
|
||||
@@ -37,10 +45,10 @@ export function createMethodMetadata(
|
||||
|
||||
if (!service) {
|
||||
const { name } = target.constructor;
|
||||
return { service: name, rpc: capitalizeFirstLetter(key) };
|
||||
return { service: name, rpc: capitalizeFirstLetter(key as string) };
|
||||
}
|
||||
if (service && !method) {
|
||||
return { service, rpc: capitalizeFirstLetter(key) };
|
||||
return { service, rpc: capitalizeFirstLetter(key as string) };
|
||||
}
|
||||
return { service, rpc: method };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export interface CustomTransportStrategy {
|
||||
listen(callback: () => void);
|
||||
close();
|
||||
}
|
||||
listen(callback: () => void): any;
|
||||
close(): any;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
export interface MessageHandlers {
|
||||
[pattern: string]: (data) => Promise<Observable<any>>;
|
||||
[pattern: string]: (data: any) => Promise<Observable<any>>;
|
||||
}
|
||||
|
||||
@@ -24,8 +24,8 @@ export class ListenerMetadataExplorer {
|
||||
}
|
||||
|
||||
public exploreMethodMetadata(
|
||||
instance,
|
||||
instancePrototype,
|
||||
instance: object,
|
||||
instancePrototype: any,
|
||||
methodName: string,
|
||||
): PatternProperties {
|
||||
const targetCallback = instancePrototype[methodName];
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
|
||||
import { ApplicationConfig } from '@nestjs/core/application-config';
|
||||
import { RuntimeException } from '@nestjs/core/errors/exceptions/runtime.exception';
|
||||
import { GuardsConsumer } from '@nestjs/core/guards/guards-consumer';
|
||||
import { GuardsContextCreator } from '@nestjs/core/guards/guards-context-creator';
|
||||
import { InstanceWrapper } from '@nestjs/core/injector/container';
|
||||
import {
|
||||
InstanceWrapper,
|
||||
NestContainer,
|
||||
} from '@nestjs/core/injector/container';
|
||||
import { InterceptorsConsumer } from '@nestjs/core/interceptors/interceptors-consumer';
|
||||
import { InterceptorsContextCreator } from '@nestjs/core/interceptors/interceptors-context-creator';
|
||||
import { PipesConsumer } from '@nestjs/core/pipes/pipes-consumer';
|
||||
@@ -19,7 +23,7 @@ export class MicroservicesModule {
|
||||
private readonly clientsContainer = new ClientsContainer();
|
||||
private listenersController: ListenersController;
|
||||
|
||||
public register(container, config) {
|
||||
public register(container: NestContainer, config: ApplicationConfig) {
|
||||
const contextCreator = new RpcContextCreator(
|
||||
new RpcProxy(),
|
||||
new ExceptionFiltersContext(container, config),
|
||||
@@ -36,7 +40,10 @@ export class MicroservicesModule {
|
||||
);
|
||||
}
|
||||
|
||||
public setupListeners(container, server: Server & CustomTransportStrategy) {
|
||||
public setupListeners(
|
||||
container: NestContainer,
|
||||
server: Server & CustomTransportStrategy,
|
||||
) {
|
||||
if (!this.listenersController) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
@@ -46,7 +53,7 @@ export class MicroservicesModule {
|
||||
);
|
||||
}
|
||||
|
||||
public setupClients(container) {
|
||||
public setupClients(container: NestContainer) {
|
||||
if (!this.listenersController) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ export class ServerGrpc extends Server implements CustomTransportStrategy {
|
||||
this.grpcClient = null;
|
||||
}
|
||||
|
||||
public deserialize(obj): any {
|
||||
public deserialize(obj: any): any {
|
||||
try {
|
||||
return JSON.parse(obj);
|
||||
} catch (e) {
|
||||
|
||||
@@ -106,7 +106,7 @@ export class ServerNats extends Server implements CustomTransportStrategy {
|
||||
);
|
||||
}
|
||||
|
||||
public handleError(stream) {
|
||||
public handleError(stream: any) {
|
||||
stream.on(ERROR_EVENT, (err: any) => this.logger.error(err));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,10 +71,15 @@ export class ServerRedis extends Server implements CustomTransportStrategy {
|
||||
}
|
||||
|
||||
public getMessageHandler(pub: RedisClient) {
|
||||
return async (channel, buffer) => this.handleMessage(channel, buffer, pub);
|
||||
return async (channel: string, buffer: string | any) =>
|
||||
this.handleMessage(channel, buffer, pub);
|
||||
}
|
||||
|
||||
public async handleMessage(channel, buffer: string | any, pub: RedisClient) {
|
||||
public async handleMessage(
|
||||
channel: string,
|
||||
buffer: string | any,
|
||||
pub: RedisClient,
|
||||
) {
|
||||
const packet = this.deserialize(buffer);
|
||||
const pattern = channel.replace(/_ack$/, '');
|
||||
const publish = this.getPublisher(pub, pattern, packet.id);
|
||||
@@ -98,7 +103,7 @@ export class ServerRedis extends Server implements CustomTransportStrategy {
|
||||
);
|
||||
}
|
||||
|
||||
public deserialize(content): ReadPacket & PacketId {
|
||||
public deserialize(content: any): ReadPacket & PacketId {
|
||||
try {
|
||||
return JSON.parse(content);
|
||||
} catch (e) {
|
||||
@@ -114,12 +119,13 @@ export class ServerRedis extends Server implements CustomTransportStrategy {
|
||||
return `${pattern}_res`;
|
||||
}
|
||||
|
||||
public handleError(stream) {
|
||||
public handleError(stream: any) {
|
||||
stream.on(ERROR_EVENT, (err: any) => this.logger.error(err));
|
||||
}
|
||||
|
||||
public getClientOptions(): Partial<ClientOpts> {
|
||||
const retry_strategy = options => this.createRetryStrategy(options);
|
||||
const retry_strategy = (options: RetryStrategyOptions) =>
|
||||
this.createRetryStrategy(options);
|
||||
return {
|
||||
retry_strategy,
|
||||
};
|
||||
|
||||
@@ -59,10 +59,10 @@ export class ServerRMQ extends Server implements CustomTransportStrategy {
|
||||
|
||||
public async start(callback?: () => void) {
|
||||
this.server = this.createClient();
|
||||
this.server.on(CONNECT_EVENT, _ => {
|
||||
this.server.on(CONNECT_EVENT, (_: any) => {
|
||||
this.channel = this.server.createChannel({
|
||||
json: false,
|
||||
setup: channel => this.setupChannel(channel, callback),
|
||||
setup: (channel: any) => this.setupChannel(channel, callback),
|
||||
});
|
||||
});
|
||||
this.server.on(DISCONNECT_EVENT, (err: any) => {
|
||||
@@ -77,7 +77,7 @@ export class ServerRMQ extends Server implements CustomTransportStrategy {
|
||||
public async setupChannel(channel: any, callback: Function) {
|
||||
await channel.assertQueue(this.queue, this.queueOptions);
|
||||
await channel.prefetch(this.prefetchCount, this.isGlobalPrefetchCount);
|
||||
channel.consume(this.queue, msg => this.handleMessage(msg), {
|
||||
channel.consume(this.queue, (msg: any) => this.handleMessage(msg), {
|
||||
noAck: true,
|
||||
});
|
||||
callback();
|
||||
@@ -101,7 +101,7 @@ export class ServerRMQ extends Server implements CustomTransportStrategy {
|
||||
await handler(packet.data),
|
||||
) as Observable<any>;
|
||||
|
||||
const publish = data =>
|
||||
const publish = <T>(data: T) =>
|
||||
this.sendMessage(data, properties.replyTo, properties.correlationId);
|
||||
|
||||
response$ && this.send(response$, publish);
|
||||
|
||||
@@ -39,14 +39,17 @@ export class ServerTCP extends Server implements CustomTransportStrategy {
|
||||
this.server.close();
|
||||
}
|
||||
|
||||
public bindHandler(socket) {
|
||||
public bindHandler<T extends Record<string, any>>(socket: T) {
|
||||
const readSocket = this.getSocketInstance(socket);
|
||||
readSocket.on(MESSAGE_EVENT, async msg =>
|
||||
readSocket.on(MESSAGE_EVENT, async (msg: ReadPacket & PacketId) =>
|
||||
this.handleMessage(readSocket, msg),
|
||||
);
|
||||
}
|
||||
|
||||
public async handleMessage(socket, packet: ReadPacket & PacketId) {
|
||||
public async handleMessage<T extends Record<string, any>>(
|
||||
socket: T,
|
||||
packet: ReadPacket & PacketId,
|
||||
) {
|
||||
const pattern = !isString(packet.pattern)
|
||||
? JSON.stringify(packet.pattern)
|
||||
: packet.pattern;
|
||||
@@ -91,7 +94,7 @@ export class ServerTCP extends Server implements CustomTransportStrategy {
|
||||
this.server.on(CLOSE_EVENT, this.handleClose.bind(this));
|
||||
}
|
||||
|
||||
private getSocketInstance(socket): JsonSocket {
|
||||
private getSocketInstance<T>(socket: T): JsonSocket {
|
||||
return new JsonSocket(socket);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export abstract class Server {
|
||||
|
||||
public addHandler(
|
||||
pattern: any,
|
||||
callback: (data) => Promise<Observable<any>>,
|
||||
callback: <T>(data: T) => Promise<Observable<any>>,
|
||||
) {
|
||||
const key = isString(pattern) ? pattern : JSON.stringify(pattern);
|
||||
this.messageHandlers[key] = callback;
|
||||
@@ -30,7 +30,7 @@ export abstract class Server {
|
||||
|
||||
public getHandlerByPattern(
|
||||
pattern: string,
|
||||
): (data) => Promise<Observable<any>> | null {
|
||||
): <T>(data: T) => Promise<Observable<any>> | null {
|
||||
return this.messageHandlers[pattern] ? this.messageHandlers[pattern] : null;
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ export abstract class Server {
|
||||
.subscribe((response: any) => respond({ err: null, response }));
|
||||
}
|
||||
|
||||
public transformToObservable<T = any>(resultOrDeffered): Observable<T> {
|
||||
public transformToObservable<T = any>(resultOrDeffered: any): Observable<T> {
|
||||
if (resultOrDeffered instanceof Promise) {
|
||||
return fromPromise(resultOrDeffered);
|
||||
} else if (!(resultOrDeffered && isFunction(resultOrDeffered.subscribe))) {
|
||||
@@ -58,10 +58,10 @@ export abstract class Server {
|
||||
return resultOrDeffered;
|
||||
}
|
||||
|
||||
public getOptionsProp<T extends { options? }>(
|
||||
public getOptionsProp<T extends { options?: any }>(
|
||||
obj: MicroserviceOptions['options'],
|
||||
prop: keyof T['options'],
|
||||
defaultValue = undefined,
|
||||
defaultValue: any = undefined,
|
||||
) {
|
||||
return obj ? obj[prop as string] : defaultValue;
|
||||
}
|
||||
|
||||
@@ -82,7 +82,9 @@ export class TestingModule extends NestApplicationContext {
|
||||
return new ExpressAdapter(httpAdapter);
|
||||
}
|
||||
|
||||
private applyLogger(options: NestApplicationContextOptions | undefined) {
|
||||
private applyLogger(
|
||||
options: NestApplicationContextOptions | undefined,
|
||||
): void {
|
||||
if (!options || !options.logger) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"module": "commonjs",
|
||||
"declaration": true,
|
||||
"noImplicitAny": false,
|
||||
"suppressImplicitAnyIndexErrors": true,
|
||||
"noUnusedLocals": false,
|
||||
"removeComments": false,
|
||||
"noLib": false,
|
||||
|
||||
@@ -93,7 +93,7 @@ export class WsAdapter implements WebSocketAdapter {
|
||||
}
|
||||
|
||||
public bindMessageHandler(
|
||||
buffer,
|
||||
buffer: any,
|
||||
handlers: MessageMappingProperties[],
|
||||
transform: (data: any) => Observable<any>,
|
||||
): Observable<any> {
|
||||
|
||||
@@ -4,7 +4,6 @@ export const GATEWAY_SERVER_METADATA = '__isSocketServer';
|
||||
export const GATEWAY_METADATA = '__isGateway';
|
||||
export const NAMESPACE_METADATA = 'namespace';
|
||||
export const PORT_METADATA = 'port';
|
||||
export const GATEWAY_MIDDLEWARES = '__gatewayMiddleware';
|
||||
export const GATEWAY_OPTIONS = '__gatewayOptions';
|
||||
|
||||
export const CONNECTION_EVENT = 'connection';
|
||||
|
||||
@@ -12,7 +12,7 @@ export class ExceptionFiltersContext extends BaseExceptionFilterContext {
|
||||
|
||||
public create(
|
||||
instance: Controller,
|
||||
callback: (client, data) => any,
|
||||
callback: <TClient>(client: TClient, data: any) => any,
|
||||
module: string,
|
||||
): WsExceptionsHandler {
|
||||
this.moduleContext = module;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user