Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ const storage = {
async getItem(cacheKey: string) {
return redis.get(cacheKey)
},
async setItem(cacheKey: string, cacheValue: any) {
async setItem(cacheKey: string, cacheValue: any, persistOptions: PersistOptions) {
// Use px or ex depending on whether you use milliseconds or seconds for your ttl
// It is recommended to set ttl to your maxTimeToLive (it has to be more than it)
await redis.set(cacheKey, cacheValue, 'px', ttl)
Expand Down Expand Up @@ -178,6 +178,16 @@ const result = await swr.persist(cacheKey, cacheValue)

The value will be passed through the `serialize` method you optionally provided when you instantiated the `swr` helper.

Additional options can be passed as a third argument and propagated to the storage's `setItem` method.

```typescript
const cacheKey = 'your-cache-key'
const cacheValue = { something: 'useful' }
const persistOptions = { overrideOption: 1000 }
const result = await swr.persist(cacheKey, cacheValue, persistOptions)
```


#### Manually read from cache

There is a convenience static method made available if you need to simply read from the underlying storage without triggering revalidation. Sometimes you just want to know if there is a value in the cache for a given key.
Expand Down
38 changes: 38 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,44 @@ describe('createStaleWhileRevalidateCache', () => {
})
expect(fn).toHaveBeenCalledTimes(1)
})

it('should persist given cache value for given key with custom storage configuration', async () => {
const swr = createStaleWhileRevalidateCache(validConfig)

const key = 'persist key'
const value = 'value'
const options = {
ttl: 1000,
}

expect(mockedLocalStorage.getItem(key)).toEqual(null)
expect(mockedLocalStorage.getItem(createTimeCacheKey(key))).toEqual(null)

const spy = jest.spyOn(mockedLocalStorage, 'setItem')
await swr.persist(key, value, options)

expect(spy).toHaveBeenCalledWith(key, value, options)

expect(mockedLocalStorage.getItem(key)).toEqual(value)
expect(mockedLocalStorage.getItem(createTimeCacheKey(key))).toEqual(
expect.any(String)
)

const fn = jest.fn(() => 'something else')
const result = await swr(key, fn)

expect(result).toMatchObject({
value,
status: 'stale',
minTimeToStale: 0,
maxTimeToLive: Infinity,
now: expect.any(Number),
cachedAt: expect.any(Number),
expireAt: Infinity,
staleAt: expect.any(Number),
})
expect(fn).toHaveBeenCalledTimes(1)
})
})

describe('swr.delete()', () => {
Expand Down
11 changes: 8 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
RetrieveCachedValueResponse,
StaleWhileRevalidateCache,
StaticMethods,
PersistOptions,
} from '../types'
import { CacheResponseStatus, EmitterEvents } from './constants'
import {
Expand Down Expand Up @@ -62,20 +63,22 @@ export function createStaleWhileRevalidateCache(
cacheTime,
serialize,
storage,
persistOptions,
}: {
cacheKey: IncomingCacheKey
cacheValue: CacheValue
cacheTime: number
serialize: NonNullable<Config['serialize']>
storage: Config['storage']
persistOptions?: PersistOptions
}): Promise<void> {
const key = getCacheKey(cacheKey)
const timeKey = createTimeCacheKey(key)

try {
await Promise.all([
storage.setItem(key, serialize(cacheValue)),
storage.setItem(timeKey, cacheTime.toString()),
storage.setItem(key, serialize(cacheValue), persistOptions),
storage.setItem(timeKey, cacheTime.toString(), persistOptions),
])
} catch (error) {
emitter.emit(EmitterEvents.cacheSetFailed, { cacheKey, error })
Expand Down Expand Up @@ -314,14 +317,16 @@ export function createStaleWhileRevalidateCache(

const persist: StaticMethods['persist'] = <CacheValue>(
cacheKey: IncomingCacheKey,
cacheValue: CacheValue
cacheValue: CacheValue,
persistOptions?: PersistOptions
) => {
return persistValue({
cacheKey,
cacheValue,
cacheTime: Date.now(),
serialize: cacheConfig.serialize,
storage: cacheConfig.storage,
persistOptions,
})
}

Expand Down
11 changes: 9 additions & 2 deletions types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
export interface Storage {
getItem(key: string): unknown | null | Promise<unknown | null>
setItem(key: string, value: unknown): void | Promise<void>
setItem(
key: string,
value: unknown,
persistOptions?: PersistOptions
): void | Promise<void>
removeItem?: (key: string) => unknown | null | Promise<unknown | null>
[key: string]: any
}
Expand Down Expand Up @@ -42,6 +46,8 @@ export type ResponseEnvelope<CacheValue> = {
staleAt: number
}

export type PersistOptions = Record<string, any>

export type StaleWhileRevalidateCache = <CacheValue>(
cacheKey: IncomingCacheKey,
fn: () => CacheValue | Promise<CacheValue>,
Expand All @@ -55,6 +61,7 @@ export type StaticMethods = {
) => Promise<RetrieveCachedValueResponse<CacheValue>>
persist: <CacheValue>(
cacheKey: IncomingCacheKey,
cacheValue: CacheValue
cacheValue: CacheValue,
persistOptions?: PersistOptions
) => Promise<void>
}