Skip to content

Commit 1a06fed

Browse files
authored
fix: wrong scope in captureMethod (#1026)
* Update Tracer.ts using the captureMethod decorator the "this" is no longer the original obj so changing to the target fixes this * added test to verify change to captureMethod. * fix to code formting to pass tests * reverted Tracer.ts and reedited for a clean commit * issue with the last commit, fixing Tracter again * fix lint issues
1 parent 1bd7808 commit 1a06fed

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

Diff for: packages/tracer/src/Tracer.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -424,7 +424,7 @@ class Tracer extends Utility implements TracerInterface {
424424
return this.provider.captureAsyncFunc(`### ${originalMethod.name}`, async subsegment => {
425425
let result;
426426
try {
427-
result = await originalMethod.apply(this, [...args]);
427+
result = await originalMethod.apply(target, [...args]);
428428
this.addResponseAsMetadata(result, originalMethod.name);
429429
} catch (error) {
430430
this.addErrorAsMetadata(error as Error);

Diff for: packages/tracer/tests/unit/Tracer.test.ts

+36
Original file line numberDiff line numberDiff line change
@@ -973,6 +973,42 @@ describe('Class: Tracer', () => {
973973

974974
});
975975

976+
test('when used as decorator and when calling other methods/props in the class they are called in the orginal scope', async () => {
977+
978+
// Prepare
979+
const tracer: Tracer = new Tracer();
980+
const newSubsegment: Segment | Subsegment | undefined = new Subsegment('### dummyMethod');
981+
jest.spyOn(tracer.provider, 'getSegment')
982+
.mockImplementation(() => newSubsegment);
983+
setContextMissingStrategy(() => null);
984+
985+
class Lambda implements LambdaInterface {
986+
987+
@tracer.captureMethod()
988+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
989+
// @ts-ignore
990+
public async dummyMethod(): Promise<string> {
991+
return `otherMethod:${this.otherMethod()}`;
992+
}
993+
994+
@tracer.captureLambdaHandler()
995+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
996+
// @ts-ignore
997+
public async handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {
998+
return <TResult>(await this.dummyMethod() as unknown);
999+
}
1000+
1001+
public otherMethod(): string {
1002+
return 'otherMethod';
1003+
}
1004+
1005+
}
1006+
1007+
// Act / Assess
1008+
expect(await (new Lambda()).handler({}, context, () => console.log('Lambda invoked!'))).toEqual('otherMethod:otherMethod');
1009+
1010+
});
1011+
9761012
});
9771013

9781014
describe('Method: captureAWS', () => {

0 commit comments

Comments
 (0)