@tsed/common
Version:
A TypeScript Framework on top of Express
68 lines • 1.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Use = void 0;
const core_1 = require("@tsed/core");
const schema_1 = require("@tsed/schema");
const index_1 = require("../../constants/index");
function mapOptions(args) {
let method = undefined;
let path = undefined;
const middlewares = args.filter((arg) => {
if (typeof arg === "string" && index_1.HTTP_METHODS.includes(arg)) {
method = arg;
return false;
}
if (typeof arg === "string" || arg instanceof RegExp) {
path = arg ? arg : "/";
return false;
}
return !!arg;
});
return {
path,
method,
middlewares
};
}
/**
* Mounts the specified middleware function or functions at the specified path: the middleware function is executed when
* the base of the requested path matches `path.
*
* ```typescript
* @Controller('/')
* @Use(Middleware1)
* export class Ctrl {
*
* @Get('/')
* @Use(Middleware2)
* get() { }
* }
*
* ```
*
* @returns {Function}
* @param args
* @decorator
* @operation
*/
function Use(...args) {
return schema_1.JsonEntityFn((entity, parameters) => {
switch (entity.decoratorType) {
case core_1.DecoratorTypes.METHOD:
const endpoint = entity;
const options = mapOptions(args);
options.path && schema_1.OperationPath(options.method || schema_1.OperationMethods.CUSTOM, options.path)(...parameters);
endpoint.use(args);
break;
case core_1.DecoratorTypes.CLASS:
entity.store.merge("middlewares", {
use: args
});
break;
default:
throw new core_1.UnsupportedDecoratorType(Use, parameters);
}
});
}
exports.Use = Use;
//# sourceMappingURL=use.js.map