UNPKG

@halsp/core

Version:

面向云的现代渐进式轻量 Node.js 框架

126 lines 3.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Startup = void 0; const types_1 = require("util/types"); const logger_1 = require("./logger.cjs"); const middlewares_1 = require("./middlewares/index.cjs"); const hook_manager_1 = require("./hook/hook.manager.cjs"); const hook_1 = require("./hook/index.cjs"); const hook_exec_1 = require("./hook/hook.exec.cjs"); class Startup { constructor() { if (!process.env.NODE_ENV) { process.env.NODE_ENV = "production"; } } #mds = []; use(lambda) { this.#mds.push(() => new middlewares_1.LambdaMiddleware(lambda)); return this; } add(md, type) { if (type) { this.#mds.push([md, type]); } else { this.#mds.push(md); } return this; } hook(arg1, arg2, arg3) { let mh; let type; let isGlobal; if (typeof arg1 == "function") { mh = arg1; type = hook_1.HookType.BeforeInvoke; isGlobal = arg2; } else { type = arg1; mh = arg2; isGlobal = arg3; } if (type == hook_1.HookType.Context || type == hook_1.HookType.Begining || type == hook_1.HookType.Initialization) { isGlobal = true; } if (isGlobal) { hook_manager_1.HookManager.addGlobalHook(this, { hook: mh, type: type }); } else { this.use(async (ctx, next) => { hook_manager_1.HookManager.addHook(ctx, { hook: mh, type: type }); await next(); }); } return this; } async invoke(...args) { const ctx = await (0, hook_exec_1.execContextHooks)(this, args); Object.defineProperty(ctx, "startup", { configurable: true, get: () => this, }); if (!this.#mds.length) { return ctx.res; } if (false == (await (0, hook_exec_1.execBeginingHooks)(ctx))) { return ctx.res; } await (0, middlewares_1.invokeMiddlewares)(ctx, this.#mds, true); return ctx.res; } async initialize(...args) { await (0, hook_exec_1.execInitializationHooks)(this, args); } logger = new logger_1.BaseLogger(); extend(name, fn) { const beforeFn = this[name]; this[name] = (...args) => { let beforeResult; if (beforeFn) { beforeResult = beforeFn.call(this, ...args); } let currentResult = fn.call(this, ...args); if (!(0, types_1.isPromise)(beforeResult) && !(0, types_1.isPromise)(currentResult)) { return currentResult ?? beforeResult; } return new Promise(async (resolve, reject) => { if ((0, types_1.isPromise)(beforeResult)) { beforeResult = await beforeResult.catch((err) => { reject(err); }); } if ((0, types_1.isPromise)(currentResult)) { currentResult = await currentResult.catch((err) => { reject(err); }); } resolve(currentResult ?? beforeResult); }); }; return this; } call(when, fn) { if (!when(this)) { return this; } fn(this); return this; } #registers = []; get registers() { return this.#registers; } register(pattern, handler) { this.#registers.push({ pattern, handler, }); return this; } } exports.Startup = Startup; //# sourceMappingURL=startup.js.map