UNPKG

@halsp/core

Version:

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

122 lines 3.58 kB
import { isPromise } from "util/types"; import { BaseLogger } from "./logger.mjs"; import { invokeMiddlewares, LambdaMiddleware, } from "./middlewares/index.mjs"; import { HookManager } from "./hook/hook.manager.mjs"; import { HookType } from "./hook/index.mjs"; import { execBeginingHooks, execContextHooks, execInitializationHooks, } from "./hook/hook.exec.mjs"; export class Startup { constructor() { if (!process.env.NODE_ENV) { process.env.NODE_ENV = "production"; } } #mds = []; use(lambda) { this.#mds.push(() => new 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 = HookType.BeforeInvoke; isGlobal = arg2; } else { type = arg1; mh = arg2; isGlobal = arg3; } if (type == HookType.Context || type == HookType.Begining || type == HookType.Initialization) { isGlobal = true; } if (isGlobal) { HookManager.addGlobalHook(this, { hook: mh, type: type }); } else { this.use(async (ctx, next) => { HookManager.addHook(ctx, { hook: mh, type: type }); await next(); }); } return this; } async invoke(...args) { const ctx = await execContextHooks(this, args); Object.defineProperty(ctx, "startup", { configurable: true, get: () => this, }); if (!this.#mds.length) { return ctx.res; } if (false == (await execBeginingHooks(ctx))) { return ctx.res; } await invokeMiddlewares(ctx, this.#mds, true); return ctx.res; } async initialize(...args) { await execInitializationHooks(this, args); } logger = new 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 (!isPromise(beforeResult) && !isPromise(currentResult)) { return currentResult ?? beforeResult; } return new Promise(async (resolve, reject) => { if (isPromise(beforeResult)) { beforeResult = await beforeResult.catch((err) => { reject(err); }); } if (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; } } //# sourceMappingURL=startup.js.map