phecda-server
Version:
server framework that provide IOC/type-reuse/http&rpc-adaptor
104 lines (102 loc) • 2.85 kB
JavaScript
import {
Context,
createControllerMetaMap,
detectAopDep
} from "../../chunk-WST6E6MQ.mjs";
import {
HMR,
__name
} from "../../chunk-URKOYTBU.mjs";
// src/rpc/rabbitmq/bind.ts
import Debug from "debug";
var debug = Debug("phecda-server/rabbitmq");
async function bind(ch, { moduleMap, meta }, opts = {}) {
const { globalGuards, globalFilter, globalPipe, globalAddons = [], defaultQueue } = opts;
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,
addons: globalAddons
}, "rpc");
const existQueue = /* @__PURE__ */ new Set();
Context.applyAddons(globalAddons, ch, "rabbitmq");
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);
await ch.assertQueue(queue);
ch.consume(queue, handleRequest, {
noAck: true
});
}
}
}
}
__name(subscribeQueues, "subscribeQueues");
async function handleRequest(msg) {
function send(queue, data) {
ch.sendToQueue(queue, Buffer.from(JSON.stringify(data)));
}
__name(send, "send");
if (msg) {
const data = JSON.parse(msg.content.toString());
const { tag, method, id, queue: clientQueue, _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;
const aop = Context.getAop(meta2, {
globalFilter,
globalGuards,
globalPipe
});
const context = new Context({
type: "rabbitmq",
category: "rpc",
moduleMap,
meta: meta2,
tag,
method,
args,
id,
ch,
msg,
isEvent,
queue: msg.fields.routingKey
});
await context.run(aop, (returnData) => {
if (!isEvent) send(clientQueue, {
data: returnData,
id
});
}, (err) => {
if (!isEvent) send(clientQueue, {
data: err,
id,
error: true
});
});
}
}
__name(handleRequest, "handleRequest");
subscribeQueues();
HMR(async () => {
for (const queue of existQueue) await ch.deleteQueue(queue);
await subscribeQueues();
});
}
__name(bind, "bind");
export {
bind
};