Skip to content

Commit

Permalink
fix: wrong scope in captureMethod (#1026)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
ratscrew authored Jul 29, 2022
1 parent 1bd7808 commit 1a06fed
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/tracer/src/Tracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ class Tracer extends Utility implements TracerInterface {
return this.provider.captureAsyncFunc(`### ${originalMethod.name}`, async subsegment => {
let result;
try {
result = await originalMethod.apply(this, [...args]);
result = await originalMethod.apply(target, [...args]);
this.addResponseAsMetadata(result, originalMethod.name);
} catch (error) {
this.addErrorAsMetadata(error as Error);
Expand Down
36 changes: 36 additions & 0 deletions packages/tracer/tests/unit/Tracer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -973,6 +973,42 @@ describe('Class: Tracer', () => {

});

test('when used as decorator and when calling other methods/props in the class they are called in the orginal scope', async () => {

// Prepare
const tracer: Tracer = new Tracer();
const newSubsegment: Segment | Subsegment | undefined = new Subsegment('### dummyMethod');
jest.spyOn(tracer.provider, 'getSegment')
.mockImplementation(() => newSubsegment);
setContextMissingStrategy(() => null);

class Lambda implements LambdaInterface {

@tracer.captureMethod()
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
public async dummyMethod(): Promise<string> {
return `otherMethod:${this.otherMethod()}`;
}

@tracer.captureLambdaHandler()
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
public async handler<TEvent, TResult>(_event: TEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {
return <TResult>(await this.dummyMethod() as unknown);
}

public otherMethod(): string {
return 'otherMethod';
}

}

// Act / Assess
expect(await (new Lambda()).handler({}, context, () => console.log('Lambda invoked!'))).toEqual('otherMethod:otherMethod');

});

});

describe('Method: captureAWS', () => {
Expand Down

0 comments on commit 1a06fed

Please sign in to comment.