21128: cleanup, renamed some types Arvados-DCO-1.1-Signed-off-by: Lisa Knox <lisa...
[arvados.git] / src / websocket / websocket-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { AuthService } from 'services/auth-service/auth-service';
6 import { ResourceEventMessage } from './resource-event-message';
7 import { camelCase } from 'lodash';
8 import { CommonResourceService } from "services/common-service/common-resource-service";
9
10 type MessageListener = (message: ResourceEventMessage) => void;
11
12 export class WebSocketService {
13     private ws: WebSocket;
14     private messageListener: MessageListener;
15
16     constructor(private url: string, private authService: AuthService) { }
17
18     connect() {
19         if (this.ws) {
20             this.ws.close();
21         }
22         this.ws = new WebSocket(this.getUrl());
23         this.ws.addEventListener('message', this.handleMessage);
24         this.ws.addEventListener('open', this.handleOpen);
25     }
26
27     setMessageListener = (listener: MessageListener) => {
28         this.messageListener = listener;
29     }
30
31     private getUrl() {
32         return `${this.url}?api_token=${this.authService.getApiToken()}`;
33     }
34
35     private handleMessage = (event: MessageEvent) => {
36         if (this.messageListener) {
37             const data = JSON.parse(event.data);
38             const message = CommonResourceService.mapKeys(camelCase)(data);
39             this.messageListener(message);
40         }
41     }
42
43     private handleOpen = () => {
44         this.ws.send('{"method":"subscribe"}');
45     }
46
47 }