1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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";
10 type MessageListener = (message: ResourceEventMessage) => void;
12 export class WebSocketService {
13 private ws: WebSocket;
14 private messageListener: MessageListener;
16 constructor(private url: string, private authService: AuthService) { }
22 this.ws = new WebSocket(this.getUrl());
23 this.ws.addEventListener('message', this.handleMessage);
24 this.ws.addEventListener('open', this.handleOpen);
27 setMessageListener = (listener: MessageListener) => {
28 this.messageListener = listener;
32 return `${this.url}?api_token=${this.authService.getApiToken()}`;
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);
43 private handleOpen = () => {
44 this.ws.send('{"method":"subscribe"}');