Handle websocket authentication slightly differently to make errors easier to work with

This commit is contained in:
Dane Everitt 2019-12-21 17:31:04 -08:00
parent 02c0d934c3
commit 11c17245c2
No known key found for this signature in database
GPG key ID: EEA66103B3D71F53
2 changed files with 26 additions and 9 deletions

View file

@ -23,9 +23,9 @@ export class Websocket extends EventEmitter {
private token: string = '';
// Connects to the websocket instance and sets the token for the initial request.
connect (url: string) {
connect (url: string): this {
this.url = url;
this.socket = new Sockette(`${this.url}?token=${this.token}`, {
this.socket = new Sockette(`${this.url}`, {
onmessage: e => {
try {
let { event, args } = JSON.parse(e.data);
@ -34,11 +34,19 @@ export class Websocket extends EventEmitter {
console.warn('Failed to parse incoming websocket message.', ex);
}
},
onopen: () => this.emit('SOCKET_OPEN'),
onreconnect: () => this.emit('SOCKET_RECONNECT'),
onopen: () => {
this.emit('SOCKET_OPEN');
this.authenticate();
},
onreconnect: () => {
this.emit('SOCKET_RECONNECT');
this.authenticate();
},
onclose: () => this.emit('SOCKET_CLOSE'),
onerror: () => this.emit('SOCKET_ERROR'),
});
return this;
}
// Returns the URL connected to for the socket.
@ -48,11 +56,11 @@ export class Websocket extends EventEmitter {
// Sets the authentication token to use when sending commands back and forth
// between the websocket instance.
setToken (token: string): this {
setToken (token: string, isUpdate = false): this {
this.token = token;
if (this.url) {
this.send('auth', token);
if (isUpdate) {
this.authenticate();
}
return this;
@ -63,6 +71,12 @@ export class Websocket extends EventEmitter {
return this.token;
}
authenticate () {
if (this.url && this.token) {
this.send('auth', this.token);
}
}
close (code?: number, reason?: string) {
this.url = null;
this.token = '';