Skip to content

Commit

Permalink
fix(core): handle nested context correctly with UseCls decorator (#119)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandre-abrioux authored Feb 3, 2024
1 parent 26afd86 commit df90f30
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
16 changes: 16 additions & 0 deletions packages/core/src/lib/cls-initializers/use-cls.decorator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { CLS_ID } from '../cls.constants';
import { ClsModule } from '../cls.module';
import { ClsService } from '../cls.service';
import { UseCls } from './use-cls.decorator';
import { ClsServiceManager } from '../cls-service-manager';

@Injectable()
class TestClass {
Expand Down Expand Up @@ -38,6 +39,7 @@ class TestClass {
return {
id: this.cls.getId(),
value: this.cls.get('value'),
inheritedValue: this.cls.get('inheritedValue'),
};
}
}
Expand All @@ -61,6 +63,20 @@ describe('@UseCls', () => {
value: 'something',
});
});

it('should handle nested context', async () => {
const cls = ClsServiceManager.getClsService();
await cls.run(async () => {
cls.set('inheritedValue', 'other');
const result = await testClass.startContext('something');
expect(result).toEqual({
id: 'the-id',
value: 'something',
inheritedValue: 'other',
});
});
});

it('calls id generator and setup and uses correct this', async () => {
const result = await testClass.startContextWithIdAndSetup(
'something else',
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/lib/cls.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,10 @@ export class ClsService<S extends ClsStore = ClsStore> {
let options: ClsContextOptions;
let callback: () => any;
if (typeof optionsOrCallback === 'object') {
options = optionsOrCallback;
options = { ...new ClsContextOptions(), ...optionsOrCallback };
callback = maybeCallback;
} else {
options = { ...new ClsContextOptions(), ...optionsOrCallback };
options = new ClsContextOptions();
callback = optionsOrCallback;
}
if (!this.isActive()) return this.runWith({} as S, callback);
Expand Down

0 comments on commit df90f30

Please sign in to comment.