Skip to content

Commit

Permalink
has method for key presence check (#41)
Browse files Browse the repository at this point in the history
* feat: Adding has method for key presence check

* feat: Adding has overload signature

* chore: Moving has method below get, adding api section for has
  • Loading branch information
agmoss authored Aug 8, 2022
1 parent c72f568 commit e85a876
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,8 @@ The injectable `ClsService` provides the following API to manipulate the cls con
Set a value on the CLS context.
- **_`get`_**`(key?: string): any`
Retrieve a value from the CLS context by key. Get the whole store if key is omitted.
- **_`has`_**`(key: string): boolean`
Check if a key is in the CLS context.
- **_`getId`_**`(): string;`
Retrieve the request ID (a shorthand for `cls.get(CLS_ID)`)
- **_`enter`_**`(): void;`
Expand Down
27 changes: 27 additions & 0 deletions src/lib/cls.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,33 @@ describe('ClsService', () => {
});
});

describe('key presence', () => {
it('checks key presence (string key)', () => {
service.run(() => {
service.set('a', 1);
expect(service.has('a')).toEqual(true);
});
});
it('checks key absence (string key)', () => {
service.run(() => {
expect(service.has('b')).toEqual(false);
});
});
it('checks key presence (symbol key)', () => {
const sym = Symbol('sym');
service.run(() => {
service.set(sym, 123);
expect(service.has(sym)).toEqual(true);
});
});
it('checks key absence (symbol key)', () => {
const sym = Symbol('sym');
service.run(() => {
expect(service.has(sym)).toEqual(false);
});
});
});

describe('edge cases', () => {
it('returns undefined on nonexistent key', () => {
service.run(() => {
Expand Down
16 changes: 16 additions & 0 deletions src/lib/cls.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ export class ClsService<S extends ClsStore = ClsStore> {
return getValueFromPath(store as S, key as any) as any;
}

/**
* Check if a key is in the CLS context
* @param key the key to check
* @returns true if the key is in the CLS context
*/
has<T extends RecursiveKeyOf<S> = any>(
key: StringIfNever<T> | keyof ClsStore,
): boolean;
has(key: string | symbol): boolean {
const store = this.namespace.getStore();
if (typeof key === 'symbol') {
return !!store[key];
}
return !!getValueFromPath(store as S, key as any);
}

/**
* Retrieve the request ID (a shorthand for `cls.get(CLS_ID)`)
* @returns the request ID or undefined
Expand Down

0 comments on commit e85a876

Please sign in to comment.