Skip to content

Commit

Permalink
fix(client): make it clear the socket can be undefined, add custom er…
Browse files Browse the repository at this point in the history
…ror for unconnected state
  • Loading branch information
SimonSchick committed Jul 30, 2017
1 parent 1a044f9 commit ba89ac1
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/Client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,14 @@ export interface Strike {
deviation: number;
}

export class NotConnectedError extends Error {
constructor (public readonly client: Client) {
super('Client not connected');
}
}

export class Client extends EventEmitter {
private socket: WebSocket;
private socket: WebSocket | undefined;

constructor (private socketFactory: SocketFactory) {
super();
Expand Down Expand Up @@ -122,7 +128,7 @@ export class Client extends EventEmitter {
return this;
}

public getSocket () {
public getSocket (): WebSocket | undefined {
return this.socket;
}

Expand All @@ -144,6 +150,9 @@ export class Client extends EventEmitter {
* Closes the connection to the remote API and detaches all listeners.
*/
public close () {
if (!this.socket) {
throw new NotConnectedError(this);
}
this.socket.close();
this.removeAllListeners();
}
Expand All @@ -154,7 +163,7 @@ export class Client extends EventEmitter {
*/
public setArea(from: GeoLocation, to: GeoLocation) {
if (!this.socket) {
throw new Error('Socket not connected');
throw new NotConnectedError(this);
}
this.sendJSON({
west: from.longitude,
Expand Down Expand Up @@ -201,6 +210,6 @@ export class Client extends EventEmitter {
}

private sendJSON(data: any) {
this.socket.send(JSON.stringify(data));
this.socket!.send(JSON.stringify(data));
}
}

0 comments on commit ba89ac1

Please sign in to comment.