Skip to content

Commit

Permalink
feat: useStorage generic support (#1279)
Browse files Browse the repository at this point in the history
  • Loading branch information
maou-shonen authored Jun 21, 2023
1 parent 25b9c5c commit 0f1832c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
16 changes: 16 additions & 0 deletions docs/content/1.guide/4.storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,22 @@ await useStorage().setItem('redis:foo', { hello: 'world' })
await useStorage().getItem('redis:foo')
```

Usage with [generics](https://unstorage.unjs.io/usage#type-inference):

```ts
await useStorage().getItem<string>('foo')
// => string
await useStorage<string>().getItem('foo')
// => string

await useStorage<string>().setItem('foo', 123) // ts error

type Foo = { data: number }

await useStorage().getItem<Foo>('foo')
// => Foo
```

You can find the list of drivers on [unstorage documentation](https://unstorage.unjs.io/).

In development, Nitro adds the `cache` mountpoint using the [FS driver](https://unstorage.unjs.io/drivers/fs) writting to `.nitro/cache` or `.nuxt/cache` if using [Nuxt](https://nuxt.com).
Expand Down
8 changes: 5 additions & 3 deletions src/runtime/storage.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { Storage } from "unstorage";
import type { Storage, StorageValue } from "unstorage";
import { prefixStorage } from "unstorage";
import { storage } from "#internal/nitro/virtual/storage";

export function useStorage(base = ""): Storage {
return base ? prefixStorage(storage, base) : storage;
export function useStorage<T extends StorageValue = StorageValue>(
base = ""
): Storage<T> {
return base ? prefixStorage<T>(storage, base) : storage;
}

0 comments on commit 0f1832c

Please sign in to comment.