Skip to content

Commit

Permalink
feat: snapshot
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Mar 11, 2021
1 parent 6e9af3e commit 7052380
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 1 deletion.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
File renamed without changes.
20 changes: 20 additions & 0 deletions test/snapshot.test.ts
Original file line number Diff line number Diff line change
@@ -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' })
})
})

0 comments on commit 7052380

Please sign in to comment.