@jsonjoy.com/reactive-rpc
Version:
Reactive-RPC is a library for building reactive APIs over WebSocket, HTTP, and other RPCs.
111 lines • 4.01 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWebSocketMock = void 0;
const utf8_1 = require("@jsonjoy.com/util/lib/strings/utf8");
const constants_1 = require("./constants");
const createWebSocketMock = (params) => {
var _a;
const WebSocketMock = (_a = class WebSocketMock {
get bufferedAmount() {
return this._bufferedAmount;
}
get extensions() {
return '';
}
get protocol() {
return this._protocol instanceof Array ? this._protocol.join(',') : this._protocol;
}
get readyState() {
return this._readyState;
}
constructor(url, _protocol = '') {
this.url = url;
this._protocol = _protocol;
this.CONNECTING = 0;
this.OPEN = 1;
this.CLOSING = 2;
this.CLOSED = 3;
this.onclose = null;
this.onerror = null;
this.onmessage = null;
this.onopen = null;
this.binaryType = 'blob';
this._readyState = constants_1.WebSocketState.CONNECTING;
this._bufferedAmount = 0;
}
close(code, reason) {
if (!params.onClose)
return;
params.onClose(code, reason);
}
send(data) {
if (typeof data === 'string') {
this._bufferedAmount += (0, utf8_1.utf8Size)(data);
}
else if (ArrayBuffer.isView(data)) {
this._bufferedAmount += data.byteLength;
}
else if (data && typeof data === 'object') {
if (data.byteLength !== undefined) {
this._bufferedAmount += Number(data.byteLength);
}
else if (data.size !== undefined) {
this._bufferedAmount += Number(data.size);
}
}
if (!params.onSend)
return;
params.onSend(data);
}
addEventListener() {
throw new Error('not implemented');
}
removeEventListener() {
throw new Error('not implemented');
}
dispatchEvent() {
throw new Error('not implemented');
}
_extendParams(newParams) {
Object.assign(params, newParams);
}
_open() {
this._readyState = constants_1.WebSocketState.OPEN;
if (typeof this.onopen === 'function') {
this.onopen.call(this, new Event('open'));
}
}
_close(code, reason, wasClean) {
if (this._readyState === constants_1.WebSocketState.CLOSED)
throw new Error('Mock WebSocket already closed.');
this._readyState = constants_1.WebSocketState.CLOSED;
if (!this.onclose)
return;
const event = {
code,
reason,
wasClean,
};
this.onclose.call(this, event);
}
_error() {
if (!this.onerror)
return;
this.onerror.call(this, new Event('error'));
}
_message(message) {
if (!this.onmessage)
return;
const event = { data: message };
this.onmessage.call(this, event);
}
},
_a.CONNECTING = 0,
_a.OPEN = 1,
_a.CLOSING = 2,
_a.CLOSED = 3,
_a);
return WebSocketMock;
};
exports.createWebSocketMock = createWebSocketMock;
//# sourceMappingURL=mock.js.map