| 14 | }; |
| 15 | |
| 16 | export class WebSocketClient { |
| 17 | url: string; |
| 18 | socket: WebSocket; |
| 19 | queue: any[] = []; |
| 20 | eventStream: Stream<any> = new Stream(); |
| 21 | promises: {[id: string]: PromiseData<void>} = {}; |
| 22 | subscribers: {[path: string]: any} = {}; |
| 23 | lastId: number = 0; |
| 24 | |
| 25 | constructor(url: string, websocketProvider: (url: string) => WebSocket) { |
| 26 | this.url = url; |
| 27 | |
| 28 | this.socket = websocketProvider(this.url); |
| 29 | this.socket.onopen = this.onOpen; |
| 30 | this.socket.onmessage = this.onMessage; |
| 31 | } |
| 32 | |
| 33 | onOpen = (ev: Event) => { |
| 34 | this.flush(); |
| 35 | } |
| 36 | |
| 37 | onMessage = (ev: MessageEvent) => { |
| 38 | const data = JSON.parse(ev.data); |
| 39 | |
| 40 | // response message |
| 41 | if (data.code !== null && data.code !== undefined) { |
| 42 | const id: string = data._id; |
| 43 | if (id in this.promises) { |
| 44 | const promise = this.promises[id]; |
| 45 | if (data.code === 200) { |
| 46 | promise.resolve(); |
| 47 | } else { |
| 48 | promise.reject(new Error(data)); |
| 49 | } |
| 50 | } |
| 51 | } else { |
| 52 | // status update message |
| 53 | setTimeout(() => this.eventStream.push(data), 0); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /* sends data via the websocket message. |
| 58 | Returns a promise, which will be resolved once a response message with the same id has been |
| 59 | received has the same id |
| 60 | */ |
| 61 | send(data: any) { |
| 62 | // add _id to each message |
| 63 | const id = this.generateId(); |
| 64 | data._id = id; |
| 65 | |
| 66 | const promiseData = {} as PromiseData<void>; |
| 67 | promiseData.promise = new Promise<void>((resolve, reject) => { |
| 68 | promiseData.resolve = resolve; |
| 69 | promiseData.reject = reject; |
| 70 | }); |
| 71 | this.promises[id] = promiseData; |
| 72 | |
| 73 | const jsonData = JSON.stringify(data); |