UNPKG

phecda-server

Version:

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

102 lines (100 loc) 2.81 kB
import { Context, createControllerMetaMap, detectAopDep } from "../../chunk-WST6E6MQ.mjs"; import { HMR, __name } from "../../chunk-URKOYTBU.mjs"; // src/rpc/nats/bind.ts import { StringCodec } from "nats"; import Debug from "debug"; var debug = Debug("phecda-server/nats"); async function bind(nc, { moduleMap, meta }, opts = {}) { const { globalGuards, globalFilter, globalPipe, globalAddons = [], defaultQueue } = opts; const sc = StringCodec(); const subscriptionMap = {}; 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, { addons: globalAddons, guards: globalGuards }, "rpc"); Context.applyAddons(globalAddons, nc, "nats"); 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 } } = meta2; if (rpc) { const queue = rpc.queue || defaultQueue || tag; if (existQueue.has(queue)) continue; existQueue.add(queue); subscriptionMap[queue] = nc.subscribe(queue, { queue, callback: handleRequest }); } } } } __name(subscribeQueues, "subscribeQueues"); async function handleRequest(_, msg) { const data = JSON.parse(sc.decode(msg.data)); const { tag, method, id, _ps, args } = 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) msg.respond("{}"); const aop = Context.getAop(meta2, { globalFilter, globalGuards, globalPipe }); const context = new Context({ type: "nats", category: "rpc", moduleMap, meta: meta2, tag, method, args, id, msg, isEvent, // @ts-expect-error nats ts problem queue: msg._msg.subject.toString() }); await context.run(aop, (returnData) => { if (!isEvent) msg.respond(sc.encode(JSON.stringify({ data: returnData, id }))); }, (err) => { if (!isEvent) msg.respond(sc.encode(JSON.stringify({ data: err, error: true, id }))); }); } __name(handleRequest, "handleRequest"); subscribeQueues(); HMR(async () => { for (const i in subscriptionMap) subscriptionMap[i].unsubscribe(); await subscribeQueues(); }); } __name(bind, "bind"); export { bind };