UNPKG

@foal/core

Version:

Full-featured Node.js framework, with no complexity

83 lines (82 loc) 2.85 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Hook = Hook; exports.getHookFunction = getHookFunction; exports.getHookFunctions = getHookFunctions; exports.MergeHooks = MergeHooks; // 3p require("reflect-metadata"); // FoalTS const config_1 = require("./config"); /** * Create a hook from one or several functions. * * @export * @param {HookFunction[]} hookFunction - The function from which the hook should be created. * @returns {HookDecorator} - The hook decorator. */ function Hook(hookFunction, openApiDecorators = [], options = {}) { return (target, propertyKey) => { // Note that propertyKey can be undefined as it's an optional parameter in getMetadata. const hooks = Reflect.getOwnMetadata('hooks', target, propertyKey) || []; hooks.unshift(hookFunction); Reflect.defineMetadata('hooks', hooks, target, propertyKey); // tslint:disable-next-line if (!(options.openapi ?? config_1.Config.get('settings.openapi.useHooks', 'boolean', true))) { return; } for (const openApiDecorator of openApiDecorators.reverse()) { openApiDecorator(target, propertyKey); } }; } /** * Get the function from which the hook was made. * * @export * @param {HookDecorator} hook - The hook decorator. * @returns {HookFunction} The hook function. */ function getHookFunction(hook) { let Foo = class Foo { }; Foo = __decorate([ hook ], Foo); return Reflect.getOwnMetadata('hooks', Foo)[0]; } /** * Get the functions from which the hook was made. * * @export * @param {HookDecorator} hook - The hook decorator. * @returns {HookFunction[]} The hook functions. */ function getHookFunctions(hook) { let Foo = class Foo { }; Foo = __decorate([ hook ], Foo); return Reflect.getOwnMetadata('hooks', Foo); } /** * Group multiple hooks into a new one. * * @export * @param {...HookDecorator[]} hookDecorators - The hooks to merge. * @returns {HookDecorator} The new hook. */ function MergeHooks(...hookDecorators) { return (target, propertyKey) => { for (const hookDecorator of hookDecorators.reverse()) { hookDecorator(target, propertyKey); } }; }