@pricingmonkey/tangi
Version:
Lightweight actor library for Web Workers inspired by Akka
73 lines • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeActorContext = exports.makeAdvancedActorContext = exports.REPLY = exports.UNSAFE_REPLY = void 0;
const uuid_1 = require("uuid");
const jobs_1 = require("./jobs");
const timeout_1 = require("./timeout");
const NO_LOGGER = { warn: () => undefined };
/**
* See https://doc.akka.io/docs/akka/current/typed/interaction-patterns.html
*/
exports.UNSAFE_REPLY = Symbol.for('@reply');
/** @deprecated use UNSAFE_REPLY instead. */
exports.REPLY = Symbol.for('@reply');
const makeAdvancedActorContext = (logger = NO_LOGGER) => (messageSenderReceiver) => {
let onReceiveMessage = undefined;
const jobs = {};
messageSenderReceiver.onmessage = (ev) => {
const data = ev.data;
if (jobs[data.id]) {
jobs_1.resolveJob(jobs, data.id, data);
}
else {
if (onReceiveMessage) {
data[exports.REPLY] = data[exports.UNSAFE_REPLY] = (response) => {
reply(data.id, response);
};
const response = onReceiveMessage(data);
if (response instanceof Promise) {
return response.then(r => {
if (r !== undefined) {
reply(data.id, r);
}
});
}
else {
if (response !== undefined) {
reply(data.id, response);
}
}
}
else {
logger.warn('unhandled message: ' + JSON.stringify(data));
}
}
};
const ask = (makeMessage, options = { timeout: 30000 }) => {
const id = uuid_1.v1();
const promiseOfResult = jobs_1.assignJob(jobs, id);
messageSenderReceiver.postMessage(makeMessage(id));
return timeout_1.timeout(promiseOfResult, options.timeout);
};
const reply = (id, response) => {
if (id === undefined || id === null) {
throw new Error('cannot reply to message without id');
}
const message = { id, ...response };
messageSenderReceiver.postMessage(message);
};
const tell = (message) => {
messageSenderReceiver.postMessage(message);
};
const receiveMessage = (onMessage) => {
if (onReceiveMessage) {
logger.warn('Overriding existing receiveMessage handler!');
}
onReceiveMessage = onMessage;
};
return { ask, tell, receiveMessage };
};
exports.makeAdvancedActorContext = makeAdvancedActorContext;
const consoleLogger = { warn: (msg) => console.warn(msg) };
exports.makeActorContext = exports.makeAdvancedActorContext(consoleLogger);
//# sourceMappingURL=context.js.map