UNPKG

actionhero

Version:

actionhero.js is a multi-transport API Server with integrated cluster capabilities and delayed tasks

71 lines (70 loc) 2.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.redis = void 0; const uuid = require("uuid"); const index_1 = require("./../index"); var redis; (function (redis) { /** * Publish a message to all other Actionhero nodes in the cluster. Will be authenticated against `api.config.serverToken` * ```js * let payload = { * messageType: 'myMessageType', * serverId: api.id, * serverToken: api.config.general.serverToken, * message: 'hello!' * } * await api.redis.publish(payload) * ``` */ async function publish(payload) { const channel = index_1.config.general.channel; return index_1.api.redis.clients.client.publish(channel, JSON.stringify(payload)); } redis.publish = publish; /** * Invoke a command on all servers in this cluster. */ async function doCluster(method, args = [], connectionId, waitForResponse = false) { const messageId = uuid.v4(); const payload = { messageType: "do", serverId: index_1.id, serverToken: index_1.config.general.serverToken, messageId: messageId, method: method, connectionId: connectionId, args: args, }; // we need to be sure that we build the response-handling promise before sending the request to Redis // it is possible for another node to get and work the request before we resolve our write // see https://github.com/actionhero/actionhero/issues/1244 for more information if (waitForResponse) { return new Promise(async (resolve, reject) => { const timer = setTimeout(() => reject(new Error("RPC Timeout")), index_1.config.general.rpcTimeout); index_1.api.redis.rpcCallbacks[messageId] = { timer, resolve, reject }; try { await redis.publish(payload); } catch (e) { clearTimeout(timer); delete index_1.api.redis.rpcCallbacks[messageId]; throw e; } }); } await redis.publish(payload); } redis.doCluster = doCluster; async function respondCluster(messageId, response) { const payload = { messageType: "doResponse", serverId: index_1.id, serverToken: index_1.config.general.serverToken, messageId: messageId, response: response, }; await redis.publish(payload); } redis.respondCluster = respondCluster; })(redis = exports.redis || (exports.redis = {}));