@zlepper/rpc
Version:
Allows RPC from the main thread to a background worker thread (Of any kind), using ES6 classes.
58 lines • 1.48 kB
JavaScript
class Pipe {
clientCallback;
serverCallback;
sendToServer(message) {
const raw = JSON.stringify(message);
setTimeout(() => {
const parsed = JSON.parse(raw);
this.serverCallback?.(parsed);
}, 1);
}
sendToClient(message) {
const raw = JSON.stringify(message);
setTimeout(() => {
const parsed = JSON.parse(raw);
this.clientCallback?.(parsed);
}, 1);
}
registerClientCallback(callback) {
this.clientCallback = callback;
}
registerServerCallback(callback) {
this.serverCallback = callback;
}
}
export class TestClientConnection {
pipe;
constructor(pipe) {
this.pipe = pipe;
}
addListener(callback) {
this.pipe.registerClientCallback(callback);
}
send(message) {
this.pipe.sendToServer(message);
}
}
export class TestServerConnection {
pipe;
constructor(pipe) {
this.pipe = pipe;
}
addListener(callback) {
this.pipe.registerServerCallback(callback);
}
removeListener() {
this.pipe.registerServerCallback(undefined);
}
send(message) {
this.pipe.sendToClient(message);
}
}
export function createTestConnection() {
const pipe = new Pipe();
const client = new TestClientConnection(pipe);
const server = new TestServerConnection(pipe);
return { client, server };
}
//# sourceMappingURL=test-helpers.js.map