Skip to content

Commit

Permalink
feat(asyncMemoize): 支持外部管理缓存
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Aug 6, 2024
1 parent ccccb69 commit f9ac5b3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 8 deletions.
15 changes: 15 additions & 0 deletions src/utils/asyncMemoize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,19 @@ describe('asyncMemoize', () => {
expect(await fnMemoized(2)).toBe(2)
expect(i).toBe(2)
})

test('支持外部管理缓存', async () => {
const fn = jest.fn().mockImplementation(async () => 1)
const fnMemoized = asyncMemoize(fn)

await fnMemoized()
expect(fn).toBeCalled().toBeCalledTimes(1)

await fnMemoized()
expect(fn).toBeCalled().toBeCalledTimes(1)

fnMemoized.cache.clear()
await fnMemoized()
expect(fn).toBeCalled().toBeCalledTimes(2)
})
})
21 changes: 13 additions & 8 deletions src/utils/asyncMemoize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ export interface AsyncMemoizeOptions<
cacheTTL?: number
}

export type AsyncMemoizeCacheMap = Map<
string,
{
value: any
expiredAt: number
}
>

/**
* 异步函数执行缓存。
*
Expand All @@ -25,15 +33,11 @@ export interface AsyncMemoizeOptions<
export function asyncMemoize<T extends (...args: any[]) => Promise<any>>(
asyncFn: T,
options: AsyncMemoizeOptions<T> = {},
): T {
): T & {
cache: AsyncMemoizeCacheMap
} {
const { cacheKey = (...args: any[]) => args[0], cacheTTL } = options
const cache = new Map<
string,
{
value: any
expiredAt: number
}
>()
const cache: AsyncMemoizeCacheMap = new Map()

const call = (...args: any[]) => {
const _cacheKey = cacheKey(...args)
Expand All @@ -53,6 +57,7 @@ export function asyncMemoize<T extends (...args: any[]) => Promise<any>>(
})
return cacheValueNew
}
call.cache = cache

return call as any
}

0 comments on commit f9ac5b3

Please sign in to comment.