phecda-server
Version:
server framework that provide IOC/type-reuse/http&rpc-adaptor
103 lines (101 loc) • 2.73 kB
JavaScript
import {
Context,
createControllerMetaMap,
detectAopDep
} from "../../chunk-BLLRB5DQ.mjs";
import {
HMR,
__name
} from "../../chunk-NQ55PA2X.mjs";
// src/rpc/redis/bind.ts
import Debug from "debug";
var debug = Debug("phecda-server/redis");
function bind({ sub, pub }, { 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, {
pub,
sub
}, "redis");
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 sub.subscribe(queue);
}
}
}
}
__name(subscribeQueues, "subscribeQueues");
sub.on("message", async (channel, msg) => {
if (!existQueue.has(channel)) return;
if (msg) {
const data = JSON.parse(msg);
const { method, id, tag, queue: clientQueue, _ps, args } = data;
debug(`invoke method "${method}" in module "${tag}"`);
if (_ps !== 1) return;
const meta2 = metaMap.get(tag)[method];
const { data: { rpc: { isEvent } = {} } } = meta2;
const aop = Context.getAop(meta2, {
globalFilter,
globalGuards,
globalPipe
});
const context = new Context({
type: "redis",
category: "rpc",
moduleMap,
redis: sub,
meta: meta2,
msg,
channel,
tag,
method,
args,
id,
isEvent,
queue: channel
});
await context.run(aop, (returnData) => {
if (!isEvent) pub.publish(clientQueue, JSON.stringify({
data: returnData,
id
}));
}, (err) => {
if (!isEvent) {
pub.publish(clientQueue, JSON.stringify({
data: err,
error: true,
id
}));
}
});
}
});
subscribeQueues();
HMR(async () => {
for (const queue of existQueue) await sub.unsubscribe(queue);
subscribeQueues();
});
}
__name(bind, "bind");
export {
bind
};