Skip to content

Commit

Permalink
fix(localstorage): consider base for clear and getKeys (#529)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Dec 19, 2024
1 parent 1f2d444 commit 4aab88b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
23 changes: 17 additions & 6 deletions src/drivers/localstorage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createRequiredError, defineDriver } from "./utils";
import { createRequiredError, defineDriver, normalizeKey } from "./utils";

export interface LocalStorageOptions {
base?: string;
Expand All @@ -19,7 +19,8 @@ export default defineDriver((opts: LocalStorageOptions = {}) => {
throw createRequiredError(DRIVER_NAME, "localStorage");
}

const r = (key: string) => (opts.base ? opts.base + ":" : "") + key;
const base = opts.base ? normalizeKey(opts.base) : "";
const r = (key: string) => (base ? `${base}:` : "") + key;

let _storageListener: undefined | ((ev: StorageEvent) => void);
const _unwatch = () => {
Expand All @@ -46,16 +47,26 @@ export default defineDriver((opts: LocalStorageOptions = {}) => {
return opts.localStorage!.removeItem(r(key));
},
getKeys() {
return Object.keys(opts.localStorage!);
const allKeys = Object.keys(opts.localStorage!);
return base
? allKeys
.filter((key) => key.startsWith(`${base}:`))
.map((key) => key.slice(base.length + 1))
: allKeys;
},
clear() {
if (opts.base) {
clear(prefix) {
const _base = [base, prefix].filter(Boolean).join(":");
if (_base) {
for (const key of Object.keys(opts.localStorage!)) {
opts.localStorage?.removeItem(key);
if (key.startsWith(`${_base}:`)) {
opts.localStorage?.removeItem(key);
}
}
} else {
opts.localStorage!.clear();
}
},
dispose() {
if (opts.window && _storageListener) {
opts.window.removeEventListener("storage", _storageListener);
}
Expand Down
17 changes: 14 additions & 3 deletions test/drivers/localstorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,22 @@ describe("drivers: localstorage", () => {
});
jsdom.virtualConsole.sendTo(console);

jsdom.window.localStorage.setItem("__external_key__", "unrelated_data");

testDriver({
driver: driver({ window: jsdom.window as unknown as typeof window }),
driver: driver({
window: jsdom.window as unknown as typeof window,
base: "test",
}),
additionalTests: (ctx) => {
it("check localstorage", () => {
expect(jsdom.window.localStorage.getItem("s1:a")).toBe("test_data");
it("check localstorage", async () => {
expect(jsdom.window.localStorage.getItem("test:s1:a")).toBe(
"test_data"
);
await ctx.driver.clear!("", {});
expect(jsdom.window.localStorage.getItem("__external_key__")).toBe(
"unrelated_data"
);
});
it("watch localstorage", async () => {
const watcher = vi.fn();
Expand Down

0 comments on commit 4aab88b

Please sign in to comment.