-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
196 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import { Injectable } from '@nestjs/common'; | ||
import { Test } from '@nestjs/testing'; | ||
import { CLS_ID } from './cls.constants'; | ||
import { ClsModule } from './cls.module'; | ||
import { ClsService } from './cls.service'; | ||
import { UseCls } from './use-cls.decorator'; | ||
|
||
@Injectable() | ||
class TestClass { | ||
constructor(private readonly cls: ClsService) {} | ||
|
||
@UseCls() | ||
async startContext(value: string) { | ||
this.cls.set(CLS_ID, this.generateId()); | ||
this.cls.set('value', value); | ||
return this.useContextVariables(); | ||
} | ||
|
||
@UseCls<[string]>({ | ||
generateId: true, | ||
idGenerator: function (this: TestClass) { | ||
return this.generateId(); | ||
}, | ||
setup: (cls, value: string) => { | ||
cls.set('value', value); | ||
}, | ||
}) | ||
// eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
async startContextWithIdAndSetup(value: string) { | ||
return this.useContextVariables(); | ||
} | ||
|
||
private generateId() { | ||
return 'the-id'; | ||
} | ||
|
||
private useContextVariables() { | ||
return { | ||
id: this.cls.getId(), | ||
value: this.cls.get('value'), | ||
}; | ||
} | ||
} | ||
|
||
describe('@UseCls', () => { | ||
let testClass: TestClass; | ||
|
||
beforeEach(async () => { | ||
const module = await Test.createTestingModule({ | ||
imports: [ClsModule], | ||
providers: [TestClass], | ||
}).compile(); | ||
|
||
testClass = module.get(TestClass); | ||
}); | ||
|
||
it('wraps function with context', async () => { | ||
const result = await testClass.startContext('something'); | ||
expect(result).toEqual({ | ||
id: 'the-id', | ||
value: 'something', | ||
}); | ||
}); | ||
it('calls id generator and setup and uses correct this', async () => { | ||
const result = await testClass.startContextWithIdAndSetup( | ||
'something else', | ||
); | ||
expect(result).toEqual({ | ||
id: 'the-id', | ||
value: 'something else', | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
import 'reflect-metadata'; | ||
import { ClsServiceManager } from './cls-service-manager'; | ||
import { CLS_ID } from './cls.constants'; | ||
import { ClsDecoratorOptions } from './cls.options'; | ||
|
||
/** | ||
* Wraps the decorated method in a CLS context. | ||
*/ | ||
export function UseCls(): ( | ||
target: any, | ||
propertyKey: string | symbol, | ||
descriptor: TypedPropertyDescriptor<(...args: any) => Promise<any>>, | ||
) => void; | ||
|
||
/** | ||
* Wraps the decorated method in a CLS context. | ||
* | ||
* @param options takes similar options to the enhancers. | ||
*/ | ||
export function UseCls<TArgs extends any[]>( | ||
options: ClsDecoratorOptions<TArgs>, | ||
): ( | ||
target: any, | ||
propertyKey: string | symbol, | ||
descriptor: TypedPropertyDescriptor<(...args: TArgs) => Promise<any>>, | ||
) => void; | ||
|
||
export function UseCls<TArgs extends any[]>( | ||
maybeOptions?: ClsDecoratorOptions<TArgs>, | ||
) { | ||
return ( | ||
target: any, | ||
propertyKey: string | symbol, | ||
descriptor: TypedPropertyDescriptor<(...args: TArgs) => Promise<any>>, | ||
) => { | ||
const options = { ...new ClsDecoratorOptions(), ...maybeOptions }; | ||
const cls = ClsServiceManager.getClsService(); | ||
const original = descriptor.value; | ||
// console.log('original is', original?.toString()); | ||
if (typeof original !== 'function') { | ||
throw new Error( | ||
`The @UseCls decorator can be only used on functions, but ${propertyKey.toString()} is not a function.`, | ||
); | ||
} | ||
descriptor.value = function (...args: TArgs) { | ||
return cls.run(async () => { | ||
if (options.generateId) { | ||
const id = await options.idGenerator?.apply(this, args); | ||
cls.set<string>(CLS_ID, id); | ||
} | ||
if (options.setup) { | ||
await options.setup.apply(this, [cls, ...args]); | ||
} | ||
if (options.resolveProxyProviders) { | ||
await cls.resolveProxyProviders(); | ||
} | ||
return original.apply(this, args); | ||
}); | ||
}; | ||
copyMetadata(original, descriptor.value); | ||
}; | ||
} | ||
|
||
/** | ||
* Copies all metadata from one object to another. | ||
* Useful for overwriting function definition in | ||
* decorators while keeping all previously | ||
* attached metadata | ||
* | ||
* @param from object to copy metadata from | ||
* @param to object to copy metadata to | ||
*/ | ||
function copyMetadata(from: any, to: any) { | ||
const metadataKeys = Reflect.getMetadataKeys(from); | ||
metadataKeys.map((key) => { | ||
const value = Reflect.getMetadata(key, from); | ||
Reflect.defineMetadata(key, value, to); | ||
}); | ||
} |