Skip to content

Commit

Permalink
fix: add mock websockets client
Browse files Browse the repository at this point in the history
  • Loading branch information
spaenleh committed Jun 29, 2023
1 parent 8a03343 commit 540ce74
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export { DATA_KEYS } from './config/keys';
export { API_ROUTES } from './api/routes';

export * from './types';
export { MockWebSocket } from './ws';
1 change: 1 addition & 0 deletions src/ws/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
*/
export * from './hooks';
export { configureWebsocketClient } from './ws-client';
export { default as MockWebSocket } from './mock-ws-client';
59 changes: 59 additions & 0 deletions src/ws/mock-ws-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* Mock WebSocket class for Graasp WS protocol
*/

export default class MockWebSocket {
CLOSED: number;

OPEN: number;

readyState: number;

onopen?: () => void;

onmessage?: (msg: unknown) => void;

constructor() {
this.CLOSED = 0;
this.OPEN = 1;

this.readyState = this.OPEN;

this.send = this.send.bind(this);
this.receive = this.receive.bind(this);
this.addEventListener = this.addEventListener.bind(this);
}

send(msg: string) {
const req = JSON.parse(msg);
// acknowledge request
if (req.action.includes('subscribe')) {
const res = {
data: JSON.stringify({
realm: 'notif',
type: 'response',
status: 'success',
request: req,
}),
};
this.onmessage?.(res);
}
}

receive(msg: object) {
const event = {
data: JSON.stringify(msg),
};
this.onmessage?.(event);
}

addEventListener(
event: 'message' | 'open',
handler: (message?: unknown) => void,
) {
this[`on${event}`] = handler;
if (event === 'open') {
handler();
}
}
}

0 comments on commit 540ce74

Please sign in to comment.