diff --git a/src/storage.ts b/src/storage.ts index eb6578471..2ad0044c3 100644 --- a/src/storage.ts +++ b/src/storage.ts @@ -59,20 +59,31 @@ export function createStorage( }; const getMounts = (base: string, includeParent?: boolean) => { - return context.mountpoints - .filter( - (mountpoint) => - mountpoint.startsWith(base) || - (includeParent && base!.startsWith(mountpoint)) - ) - .map((mountpoint) => ({ - relativeBase: - base.length > mountpoint.length - ? base!.slice(mountpoint.length) - : undefined, - mountpoint, - driver: context.mounts[mountpoint]!, - })); + const mountpoints = context.mountpoints.filter( + (mountpoint) => + mountpoint.startsWith(base) || + (includeParent && base!.startsWith(mountpoint)) + ); + + // Should fallback to the root mount if no mountpoints found + if (mountpoints.length === 0) { + return [ + { + relativeBase: undefined, + mountpoint: "", + driver: context.mounts[""]!, + }, + ]; + } + + return mountpoints.map((mountpoint) => ({ + relativeBase: + base.length > mountpoint.length + ? base!.slice(mountpoint.length) + : undefined, + mountpoint, + driver: context.mounts[mountpoint]!, + })); }; const onChange: WatchCallback = (event, key) => { diff --git a/test/drivers/utils.ts b/test/drivers/utils.ts index d1b1e420f..efcb9e848 100644 --- a/test/drivers/utils.ts +++ b/test/drivers/utils.ts @@ -208,4 +208,13 @@ export function testDriver(opts: TestOptions) { await ctx.storage.clear(); expect(await ctx.storage.getKeys()).toMatchObject([]); }); + + it("clear - clear the root mount when no matched mountpoints", async () => { + const prefix = "s1"; + await ctx.storage.setItem(`${prefix}:key`, "value"); + + expect(await ctx.storage.getKeys(prefix)).toMatchObject(["s1:key"]); + await ctx.storage.clear(prefix); + expect(await ctx.storage.getKeys(prefix)).toMatchObject([]); + }); } diff --git a/test/storage.test.ts b/test/storage.test.ts index d5a2542d7..7fc0bd458 100644 --- a/test/storage.test.ts +++ b/test/storage.test.ts @@ -56,6 +56,22 @@ describe("storage", () => { ] `); + expect(storage.getMounts("/non-exist-mountpoint").map((m) => m.base)) + .toMatchInlineSnapshot(` + [ + "", + ] + `); + expect( + storage + .getMounts("/non-exist-mountpoint", { parents: true }) + .map((m) => m.base) + ).toMatchInlineSnapshot(` + [ + "", + ] + `); + expect(storage.getMounts().map((m) => m.base)).toMatchInlineSnapshot(` [ "cache:sub:",