Skip to content

Commit

Permalink
refactor: simplify Socky and small comment changes
Browse files Browse the repository at this point in the history
  • Loading branch information
enisdenjo committed Aug 27, 2020
1 parent b8104a6 commit 36b5bdb
Showing 1 changed file with 17 additions and 16 deletions.
33 changes: 17 additions & 16 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,6 @@ function createSocky() {
};

return {
get socket() {
if (!socket) {
throw new Error(
'Illegal socket access, it is not ready yet. Have you prepared it?',
);
}
return socket;
},
get state() {
return state;
},
async shouldConnect(): Promise<boolean> {
if (state.connecting) {
let waitedTimes = 0;
Expand Down Expand Up @@ -109,7 +98,13 @@ function createSocky() {
registerMessageListener(
listener: (event: MessageEvent) => void,
): Disposable {
this.socket.addEventListener('message', listener);
if (!socket) {
throw new Error(
'Illegal socket access while registering a message listener. Has Socky been prepared?',
);
}

socket.addEventListener('message', listener);
return {
dispose: () => {
// we use the internal socket here because the connection
Expand All @@ -121,8 +116,15 @@ function createSocky() {
};
},
send(data: string) {
if (this.socket.readyState === WebSocket.OPEN) {
this.socket.send(data);
// TODO-db-200827 decide if accessing missing socket during send is illegal
if (!socket) {
throw new Error(
'Illegal socket access while sending a message. Has Socky been prepared?',
);
}

if (socket.readyState === WebSocket.OPEN) {
socket.send(data);
}
},
dispose() {
Expand Down Expand Up @@ -158,7 +160,6 @@ export function createClient(options: ClientOptions): Client {
Object.entries(subscribedSinks).forEach(([, sink]) => sink.complete());
}

// Lazily uses the socket singleton to establishes a connection described by the protocol.
const socky = createSocky();
async function prepare(): Promise<void> {
if (await socky.shouldConnect()) {
Expand Down Expand Up @@ -301,8 +302,8 @@ export function createClient(options: ClientOptions): Client {
return () => {
completed = true;

// having a message listener indicates that prepare has resolved
if (messageListener) {
// having a message listener indicates that socky became ready
messageListener.dispose();
socky.send(
stringifyMessage<MessageType.Complete>({
Expand Down

0 comments on commit 36b5bdb

Please sign in to comment.