diff --git a/projects/ngneat/cashew/src/lib/cache-context.ts b/projects/ngneat/cashew/src/lib/cache-context.ts index 05efd6a..321c987 100644 --- a/projects/ngneat/cashew/src/lib/cache-context.ts +++ b/projects/ngneat/cashew/src/lib/cache-context.ts @@ -3,10 +3,12 @@ import { EMPTY, Observable } from 'rxjs'; import { CacheBucket } from './cache-bucket'; import { HttpCacheConfig } from './cache-config'; +export type CacheContextKey = string | number; + export interface ContextOptions { cache?: boolean; ttl?: number; - key?: string | ((request: HttpRequest) => string); + key?: CacheContextKey | ((request: HttpRequest) => CacheContextKey); bucket?: CacheBucket; version?: string; clearCachePredicate?( diff --git a/projects/ngneat/cashew/src/lib/key-serializer.ts b/projects/ngneat/cashew/src/lib/key-serializer.ts index ab82500..1ad5459 100644 --- a/projects/ngneat/cashew/src/lib/key-serializer.ts +++ b/projects/ngneat/cashew/src/lib/key-serializer.ts @@ -10,7 +10,7 @@ export class DefaultKeySerializer extends KeySerializer { const { key } = context; if (key) { - return typeof key === 'function' ? key(request) : key; + return (typeof key === 'function' ? key(request) : key).toString(); } return request.urlWithParams; diff --git a/projects/ngneat/cashew/src/lib/specs/key-serializer.spec.ts b/projects/ngneat/cashew/src/lib/specs/key-serializer.spec.ts new file mode 100644 index 0000000..3bdfa5d --- /dev/null +++ b/projects/ngneat/cashew/src/lib/specs/key-serializer.spec.ts @@ -0,0 +1,35 @@ +import { DefaultKeySerializer } from '../key-serializer'; +import { httpRequest } from './mocks'; + +describe('key serializer', () => { + it('serializes to string using the given number', () => { + const serializer = new DefaultKeySerializer(); + const key = serializer.serialize(null, { key: 2 }); + expect(key).toEqual('2'); + }); + + it('serializes to string using the given string', () => { + const serializer = new DefaultKeySerializer(); + const key = serializer.serialize(null, { key: 'hello' }); + expect(key).toEqual('hello'); + }); + + it('serializes to string using the given number producing function', () => { + const serializer = new DefaultKeySerializer(); + const key = serializer.serialize(null, { key: () => 2 + 2 }); + expect(key).toEqual('4'); + }); + + it('serializes to string using the given string producing function', () => { + const serializer = new DefaultKeySerializer(); + const key = serializer.serialize(null, { key: () => 'hello' + 'world' }); + expect(key).toEqual('helloworld'); + }); + + it('serializes to full url including parameters if key is absent', () => { + const serializer = new DefaultKeySerializer(); + const request = httpRequest(); + const key = serializer.serialize(request, {}); + expect(key).toEqual(request.urlWithParams); + }); +});