@nestjs/core
Version:
The core of NestJS, a TypeScript framework for Node.js backends: modules, dependency injection and the request pipeline, on Express, Fastify or node:http.
58 lines (57 loc) • 2.15 kB
JavaScript
import { Logger } from '@nestjs/common';
import { isFunction, isObject } from '@nestjs/common/internal';
import { InvalidEnhancerException } from '../errors/exceptions/invalid-enhancer.exception.js';
import { INVALID_FILTER_MESSAGE } from '../errors/messages.js';
const ENHANCER_METHODS = {
guard: 'canActivate',
interceptor: 'intercept',
pipe: 'transform',
};
/**
* Throws when the given value can't run as an enhancer of the given kind.
* Such a value used to be dropped without an error, which left the handlers
* it was bound to without it (e.g., unguarded).
*
* @param description what was bound, for the message (by default, the value)
*/
export function assertEnhancer(enhancer, kind, description = describeEnhancer(enhancer)) {
const method = ENHANCER_METHODS[kind];
if (enhancer && isFunction(enhancer[method])) {
return;
}
throw new InvalidEnhancerException(kind, method, description);
}
/**
* Warns when the given value can't run as an exception filter. Unlike the
* other enhancers, such a filter is still skipped rather than rejected: the
* exceptions it was meant to handle get the default response, so no handler
* runs without a check it relies on.
*
* @param description what was bound, for the message (by default, the value)
*/
export function warnOnInvalidFilter(filter, description = describeEnhancer(filter)) {
// A promise has a "catch" method too, but is never a filter
const isThenable = isFunction(filter?.then);
if (filter &&
!isThenable &&
isFunction(filter.catch)) {
return;
}
new Logger('ExceptionFilter').warn(INVALID_FILTER_MESSAGE(description));
}
export function describeEnhancer(value) {
if (isFunction(value)) {
return value.name ? `class ${value.name}` : 'an anonymous class';
}
if (isFunction(value?.then)) {
return 'a promise';
}
if (Array.isArray(value)) {
return 'an array';
}
if (isObject(value)) {
const name = value.constructor?.name;
return name && name !== 'Object' ? `an instance of ${name}` : 'an object';
}
return String(value);
}