From 7052380cffa27fba877be575dd46aeaee3b98e3a Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 11 Mar 2021 11:55:30 +0100 Subject: [PATCH] feat: snapshot --- README.md | 11 ++++++++++- src/storage.ts | 10 ++++++++++ test/{index.test.ts => generic.test.ts} | 0 test/snapshot.test.ts | 20 ++++++++++++++++++++ 4 files changed, 40 insertions(+), 1 deletion(-) rename test/{index.test.ts => generic.test.ts} (100%) create mode 100644 test/snapshot.test.ts diff --git a/README.md b/README.md index 8c09a7aa..b0f11e16 100644 --- a/README.md +++ b/README.md @@ -17,12 +17,12 @@ - Tree-shakable and lightweight core - Native aware value serialization and deserialization - Restore initial state (hydration) +- State snapshot WIP: - Unmount - Key expiration -- State snapshot - State compression - Watcher @@ -148,6 +148,15 @@ Removes all stored key/values. If a base is provided, only mounts matching base await storage.clear() ``` +### `snapshot(storage, base?)` + +Snapshot from all keys in specified base into a plain javascript object (string: string). Base is removed from keys. +```js +import { snapshot } from 'unstorage' + +const data = await snapshot(storage, '/etc') +``` + ### `storage.dispose()` Disposes all mounted storages to ensure there are no open-handles left. Call it before exiting process. diff --git a/src/storage.ts b/src/storage.ts index 43f4fdfd..6a028bee 100644 --- a/src/storage.ts +++ b/src/storage.ts @@ -96,6 +96,16 @@ export function createStorage (): Storage { return storage } +export async function snapshot (storage: Storage, base: string) { + base = normalizeBase(base) + const keys = await storage.getKeys(base) + const snapshot: any = {} + await Promise.all(keys.map(async (key) => { + snapshot[key.substr(base.length)] = await storage.getItem(key) + })) + return snapshot +} + async function dispose (storage: Driver) { if (typeof storage.dispose === 'function') { await asyncCall(storage.dispose) diff --git a/test/index.test.ts b/test/generic.test.ts similarity index 100% rename from test/index.test.ts rename to test/generic.test.ts diff --git a/test/snapshot.test.ts b/test/snapshot.test.ts new file mode 100644 index 00000000..4b7a8170 --- /dev/null +++ b/test/snapshot.test.ts @@ -0,0 +1,20 @@ +import { createStorage, snapshot } from '../src' + +const data = { + 'etc:conf': 'test', + 'data:foo': 'bar' +} + +describe('snapshot', () => { + it('snapshot', async () => { + const storage = createStorage() + await storage.setItems('', data) + expect(await snapshot(storage, '')).toMatchObject(data) + }) + + it('snapshot (subpath)', async () => { + const storage = createStorage() + await storage.setItems('', data) + expect(await snapshot(storage, 'etc')).toMatchObject({ conf: 'test' }) + }) +})