Skip to content

Commit

Permalink
fix: do not open a new ws connection if already existing
Browse files Browse the repository at this point in the history
  • Loading branch information
janrnc authored and arlac77 committed Nov 11, 2023
1 parent 6f9e40f commit 9279edc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,12 @@ export function websocketStore(url, initialValue, socketOptions) {
}

// we are still in the opening phase
if(openPromise) {
if (openPromise) {
return openPromise;
}
if (socket) {
return
}

socket = new WebSocket(url, socketOptions);

Expand Down
18 changes: 18 additions & 0 deletions tests/store-ava.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,21 @@ test.skip("failing subscription", async t => {

t.true(true);
});

test("should not open a new ws connection if already existing", async t => {
let counter = 0;
t.context.wss.on('connection', () => { counter += 1 })

const store = websocketStore(`ws://localhost:${t.context.port}`, "INITIAL");

const unsubscribe = store.subscribe(value => {});
await wait(300);
const anotherUnsubscribe = store.subscribe(value => {});

await wait(50);

unsubscribe();
anotherUnsubscribe();

t.is(counter, 1)
})

0 comments on commit 9279edc

Please sign in to comment.