Add WebSocketStore for handling the web socket

This commit is contained in:
Jannis Mattheis 2018-10-21 14:00:00 +02:00
parent f0f3c53563
commit dcd8469f4d
2 changed files with 63 additions and 2 deletions

View File

@ -2,11 +2,16 @@ import * as React from 'react';
import * as ReactDOM from 'react-dom';
import 'typeface-roboto';
import 'typeface-roboto-mono';
import * as UserAction from './actions/UserAction';
import './actions/defaultAxios';
import * as config from './config';
import Layout from './Layout';
import registerServiceWorker from './registerServiceWorker';
import * as Notifications from './stores/Notifications';
import {currentUser} from './stores/CurrentUser';
import AppStore from './stores/AppStore';
import {reaction} from 'mobx';
import {WebSocketStore} from './stores/WebSocketStore';
import SnackManager from './stores/SnackManager';
const defaultDevConfig = {
url: 'http://localhost:80/',
@ -35,7 +40,20 @@ declare global {
} else {
config.set(window.config || defaultDevConfig);
}
UserAction.checkIfAlreadyLoggedIn();
const ws = new WebSocketStore(SnackManager.snack);
reaction(
() => currentUser.loggedIn,
(loggedIn) => {
if (loggedIn) {
ws.listen();
} else {
ws.close();
}
AppStore.refresh();
}
);
currentUser.tryAuthenticate();
ReactDOM.render(<Layout />, document.getElementById('root'));
registerServiceWorker();
})();

View File

@ -0,0 +1,43 @@
import {SnackReporter} from './SnackManager';
import {currentUser} from './CurrentUser';
import * as config from '../config';
import NewMessagesStore from './MessagesStore';
export class WebSocketStore {
private wsActive = false;
private ws: WebSocket | null = null;
public constructor(private readonly snack: SnackReporter) {}
public listen = () => {
if (!currentUser.token() || this.wsActive) {
return;
}
this.wsActive = true;
const wsUrl = config
.get('url')
.replace('http', 'ws')
.replace('https', 'wss');
const ws = new WebSocket(wsUrl + 'stream?token=' + currentUser.token());
ws.onerror = (e) => {
this.wsActive = false;
console.log('WebSocket connection errored', e);
};
ws.onmessage = (data) => NewMessagesStore.publishSingleMessage(JSON.parse(data.data));
ws.onclose = () => {
this.wsActive = false;
currentUser.tryAuthenticate().then(() => {
this.snack('WebSocket connection closed, trying again in 30 seconds.');
setTimeout(this.listen, 30000);
});
};
this.ws = ws;
};
public close = () => this.ws && this.ws.close();
}