Extract IPC type strings into a shared module.

This commit is contained in:
Ben Newman
2018-07-17 10:27:00 -04:00
parent 2450ffe84d
commit 692b533d49
3 changed files with 25 additions and 8 deletions

View File

@@ -1,3 +1,9 @@
const {
MESSAGE_FROM_PARENT,
RESPONSE_FROM_CHILD,
CHILD_READY,
} = require("./types.js");
const callbacksByTopic = new Map;
Object.assign(exports, {
@@ -25,12 +31,12 @@ if (typeof process.send === "function") {
// When called, the callback will receive the provided payload as a
// parameter.
process.on("message", ({
type = "FROM_PARENT",
type = MESSAGE_FROM_PARENT,
responseId = null,
topic,
payload,
}) => {
if (type === "FROM_PARENT" &&
if (type === MESSAGE_FROM_PARENT &&
typeof topic === "string") {
// Keep the messages and their responses strictly ordered per topic,
// one after the last. Because we always register a non-throwing
@@ -50,7 +56,7 @@ if (typeof process.send === "function") {
}).then(results => {
if (responseId) {
process.send({
type: "FROM_CHILD",
type: RESPONSE_FROM_CHILD,
responseId,
results,
});
@@ -66,7 +72,7 @@ if (typeof process.send === "function") {
});
process.send({
type: "FROM_CHILD",
type: RESPONSE_FROM_CHILD,
responseId,
error: serializable,
});
@@ -77,7 +83,7 @@ if (typeof process.send === "function") {
// Let the parent process know this child process is ready to receive
// messages.
process.send({
type: "CHILD_READY",
type: CHILD_READY,
pid: process.pid,
});
}

View File

@@ -1,4 +1,9 @@
const uuid = require("uuid");
const {
MESSAGE_FROM_PARENT,
RESPONSE_FROM_CHILD,
CHILD_READY,
} = require("./types.js");
const hasOwn = Object.prototype.hasOwnProperty;
// Call enableSendMessage(childProcess) to define a method called
@@ -15,14 +20,14 @@ Object.assign(exports, {
});
childProcess.on("message", message => {
if (message.type === "CHILD_READY") {
if (message.type === CHILD_READY) {
const resolve = childProcessReadyResolvers.get(message.pid);
// This resolves the child.readyForMessages Promise created above.
if (typeof resolve === "function") {
resolve();
}
} else if (message.type === "FROM_CHILD") {
} else if (message.type === RESPONSE_FROM_CHILD) {
const entry = pendingMessages.get(message.responseId);
if (entry) {
if (hasOwn.call(message, "error")) {
@@ -42,7 +47,7 @@ Object.assign(exports, {
pendingMessages.set(responseId, { resolve, reject });
childProcess.send({
type: "FROM_PARENT",
type: MESSAGE_FROM_PARENT,
responseId,
topic,
payload

View File

@@ -0,0 +1,6 @@
exports.MESSAGE_FROM_PARENT = "MESSAGE_FROM_PARENT";
exports.RESPONSE_FROM_PARENT = "RESPONSE_FROM_PARENT";
exports.MESSAGE_FROM_CHILD = "MESSAGE_FROM_CHILD";
exports.RESPONSE_FROM_CHILD = "RESPONSE_FROM_CHILD";
exports.CHILD_READY = "CHILD_READY";