Skip to content

Commit

Permalink
Merge pull request #102 from Laurens-makel/#100
Browse files Browse the repository at this point in the history
feat: allow numeric values as CacheContextKey
  • Loading branch information
NetanelBasal authored Jan 9, 2024
2 parents 21fa8a9 + 1047971 commit 57f32ea
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
4 changes: 3 additions & 1 deletion projects/ngneat/cashew/src/lib/cache-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any>) => string);
key?: CacheContextKey | ((request: HttpRequest<any>) => CacheContextKey);
bucket?: CacheBucket;
version?: string;
clearCachePredicate?<T>(
Expand Down
2 changes: 1 addition & 1 deletion projects/ngneat/cashew/src/lib/key-serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
35 changes: 35 additions & 0 deletions projects/ngneat/cashew/src/lib/specs/key-serializer.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});

0 comments on commit 57f32ea

Please sign in to comment.