Skip to content

Commit

Permalink
cache-manager: add cacheId as an optional cache option, defaults to…
Browse files Browse the repository at this point in the history
… random string.

expose Cache#cacheId() method to return cacheId.
  • Loading branch information
yaronyam committed Jan 6, 2025
1 parent 6880ff6 commit 551edb1
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 5 deletions.
19 changes: 17 additions & 2 deletions packages/cache-manager/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,10 @@ const cache = createCache({ stores: [keyv] });
* `clear` - will not wait for all stores to finish.
* `wrap` - will do the same as `get` and `set` (return the first value found and not wait for all stores to finish).

- **cacheId**?: string - Defaults to random string

Unique identifier for the cache instance.

# Methods
## set
`set(key, value, [ttl]): Promise<value>`
Expand Down Expand Up @@ -352,16 +356,27 @@ See unit tests in [`test/wrap.test.ts`](./test/wrap.test.ts) for more informatio

## disconnect

`disconnect(key): Promise<void>`
`disconnect(): Promise<void>`

Will disconnect from the relevant store(s). It is highly recomended to use this when using a [Keyv](https://keyv.org/) storage adapter that requires a disconnect. For each storage adapter, the use case for when to use disconnect is different. An example is that `@keyv/redis` should be used only when you are done with the cache.
Will disconnect from the relevant store(s). It is highly recommended to use this when using a [Keyv](https://keyv.org/) storage adapter that requires a disconnect. For each storage adapter, the use case for when to use disconnect is different. An example is that `@keyv/redis` should be used only when you are done with the cache.

```ts
await cache.disconnect();
```

See unit tests in [`test/disconnect.test.ts`](./test/disconnect.test.ts) for more information.

## cacheId
`cacheId(): string`

Returns cache instance id.

```ts
const cache = createCache({cacheId: 'my-cache-id'});
cache.cacheId(); // => 'my-cache-id'
```
See unit tests in [`test/cache-id.test.ts`](./test/get.test.ts) for more information.

# Events
## set
Fired when a key has been added or changed.
Expand Down
11 changes: 8 additions & 3 deletions packages/cache-manager/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type CreateCacheOptions = {
refreshThreshold?: number;
refreshAllStores?: boolean;
nonBlocking?: boolean;
cacheId?: string;
};

export type Cache = {
Expand Down Expand Up @@ -51,6 +52,7 @@ export type Cache = {
listener: Events[E]
) => EventEmitter;
disconnect: () => Promise<undefined>;
cacheId: () => string;
};

export type Events = {
Expand All @@ -64,7 +66,7 @@ export const createCache = (options?: CreateCacheOptions): Cache => {
const eventEmitter = new EventEmitter();
const stores = options?.stores?.length ? options.stores : [new Keyv()];
const nonBlocking = options?.nonBlocking ?? false;
const cacheId = Math.random().toString(36).slice(2);
const _cacheId = options?.cacheId ?? Math.random().toString(36).slice(2);

// eslint-disable-next-line @typescript-eslint/ban-types
const get = async <T>(key: string): Promise<T | null> => {
Expand Down Expand Up @@ -251,7 +253,7 @@ export const createCache = (options?: CreateCacheOptions): Cache => {
fnc: () => T | Promise<T>,
ttl?: number | ((value: T) => number),
refreshThreshold?: number,
): Promise<T> => coalesceAsync(`${cacheId}__${key}`, async () => {
): Promise<T> => coalesceAsync(`${_cacheId}__${key}`, async () => {
let value: T | undefined;
let i = 0;
let remainingTtl: number | undefined;
Expand Down Expand Up @@ -282,7 +284,7 @@ export const createCache = (options?: CreateCacheOptions): Cache => {
const shouldRefresh = lt(remainingTtl, refreshThreshold ?? options?.refreshThreshold);

if (shouldRefresh) {
coalesceAsync(`+++${cacheId}__${key}`, fnc)
coalesceAsync(`+++${_cacheId}__${key}`, fnc)
.then(async result => {
try {
await set(options?.refreshAllStores ? stores : stores.slice(0, i + 1), key, result, resolveTtl(result));
Expand Down Expand Up @@ -316,6 +318,8 @@ export const createCache = (options?: CreateCacheOptions): Cache => {
}
};

const cacheId = () => _cacheId;

return {
get,
mget,
Expand All @@ -329,6 +333,7 @@ export const createCache = (options?: CreateCacheOptions): Cache => {
on,
off,
disconnect,
cacheId,
};
};

Expand Down
22 changes: 22 additions & 0 deletions packages/cache-manager/test/cache-id.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {Keyv} from 'keyv';
import {
beforeEach, describe, expect, it,
} from 'vitest';
import {createCache} from '../src/index.js';

describe('cacheId', () => {
let keyv: Keyv;

beforeEach(async () => {
keyv = new Keyv();
});

it('user set', () => {
const cache = createCache({stores: [keyv], cacheId: 'my-cache-id'});
expect(cache.cacheId()).toEqual('my-cache-id');
});
it('auto generated', () => {
const cache = createCache({stores: [keyv]});
expect(cache.cacheId()).toBeTypeOf('string');
});
});

0 comments on commit 551edb1

Please sign in to comment.