Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ export function prefixStorage<T extends StorageValue>(
return storage.setItems<U>(prefixedItems, commonOptions);
};

nsStorage.watch = (callback) =>
storage.watch((event, key) => {
if (key.startsWith(base)) {
callback(event, key.slice(base.length));
}
});

return nsStorage;
}

Expand Down
22 changes: 22 additions & 0 deletions test/storage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,4 +274,26 @@ describe("Regression", () => {
{ key: "key2", value: "value2" },
]);
});

it("prefixStorage watch strips prefix and filters events", async () => {
const storage = createStorage();
const pStorage = prefixStorage(storage, "ns");

const events: { event: string; key: string }[] = [];
const unwatch = await pStorage.watch((event, key) => {
events.push({ event, key });
});

await pStorage.setItem("foo", "bar");
await storage.setItem("other:x", "y");

// give the synchronous memory-driver onChange time to flush
await new Promise((resolve) => setTimeout(resolve, 10));
await unwatch();

// key delivered to the callback should be relative (no "ns:" prefix)
expect(events).toContainEqual({ event: "update", key: "foo" });
// events for keys outside the prefix must be filtered out
expect(events.every((e) => !e.key.startsWith("other"))).toBe(true);
});
});