UNPKG

phecda-server

Version:

server framework that provide IOC/type-reuse/http&rpc-adaptor

104 lines (102 loc) 2.91 kB
import { Context, createControllerMetaMap, detectAopDep } from "../../chunk-LNL3MVTR.mjs"; import { HMR, __name } from "../../chunk-ITDH2YDL.mjs"; // src/rpc/bullmq/create.ts import { Queue, Worker } from "bullmq"; import Debug from "debug"; var debug = Debug("phecda-server/bullmq"); async function create({ moduleMap, meta }, opts = {}) { const { globalGuards, globalFilter, globalPipe, workerOpts, queueOpts, defaultQueue } = opts; const workerMap = {}; const queueMap = {}; const existQueue = /* @__PURE__ */ new Set(); const metaMap = createControllerMetaMap(meta, (meta2) => { const { controller, rpc, method, tag } = meta2.data; if (controller === "rpc" && rpc?.queue !== void 0) { debug(`register method "${method}" in module "${tag}"`); return true; } }); detectAopDep(meta, { guards: globalGuards }, "rpc"); async function subscribeQueues() { existQueue.clear(); for (const [tag, record] of metaMap) { for (const method in record) { const meta2 = metaMap.get(tag)[method]; const { data: { rpc, addons } } = meta2; if (rpc) { const queue = rpc.queue || defaultQueue || tag; if (existQueue.has(queue)) continue; existQueue.add(queue); workerMap[queue] = new Worker(queue, handleRequest, workerOpts); Context.applyAddons(addons, workerMap[queue], "bullmq"); } } } } __name(subscribeQueues, "subscribeQueues"); async function handleRequest(job) { const { data } = job; const { tag, method, args, id, queue: clientQueue, _ps } = data; if (_ps !== 1) return; debug(`invoke method "${method}" in module "${tag}"`); const meta2 = metaMap.get(tag)[method]; const { data: { rpc: { isEvent } = {} } } = meta2; if (!isEvent && !(clientQueue in queueMap)) queueMap[clientQueue] = new Queue(clientQueue, queueOpts); const aop = Context.getAop(meta2, { globalFilter, globalGuards, globalPipe }); const context = new Context({ type: "bullmq", category: "rpc", moduleMap, meta: meta2, tag, method, data, args, id, queue: job.queueName, isEvent }); await context.run(aop, (returnData) => { if (!isEvent) queueMap[clientQueue].add(`${tag}-${method}`, { data: returnData, id }); }, (err) => { if (!isEvent) { queueMap[clientQueue].add(`${tag}-${method}`, { data: err, error: true, id }); } }); } __name(handleRequest, "handleRequest"); subscribeQueues(); HMR(async () => { for (const i in workerMap) await workerMap[i].close(true); for (const i in queueMap) await queueMap[i].close(); await subscribeQueues(); }); return { workerMap, queueMap }; } __name(create, "create"); export { create };