Skip to content

Commit

Permalink
fix: properly handle invalidate events
Browse files Browse the repository at this point in the history
  • Loading branch information
darrachequesne committed May 3, 2022
1 parent d42bf39 commit 938674d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,14 @@ export function createAdapter(
) {
opts.uid = opts.uid || randomId();

let isClosed = false;
let adapters = new Map<string, MongoAdapter>();
let changeStream: any;

const initChangeStream = () => {
if (isClosed) {
return;
}
if (changeStream) {
changeStream.removeAllListeners("change");
changeStream.removeAllListeners("close");
Expand All @@ -134,7 +138,11 @@ export function createAdapter(
]);

changeStream.on("change", (event: any) => {
adapters.get(event.fullDocument.nsp)?.onEvent(event);
adapters.get(event.fullDocument?.nsp)?.onEvent(event);
});

changeStream.on("error", (err: Error) => {
debug("change stream encountered an error: %s", err.message);
});

changeStream.on("close", () => {
Expand All @@ -147,6 +155,7 @@ export function createAdapter(

return function (nsp: any) {
if (!changeStream) {
isClosed = false;
initChangeStream();
}

Expand All @@ -163,6 +172,7 @@ export function createAdapter(
changeStream.removeAllListeners("close");
changeStream.close();
changeStream = null;
isClosed = true;
}

defaultClose.call(adapter);
Expand Down
6 changes: 6 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,4 +434,10 @@ describe("@socket.io/mongodb-adapter", () => {
});
});
});

it("should not throw when receiving a drop event", async () => {
await mongoClient.db("test").dropCollection("events");

await sleep(100);
});
});

0 comments on commit 938674d

Please sign in to comment.