Skip to content

Commit

Permalink
fix: apply transformer on end events
Browse files Browse the repository at this point in the history
  • Loading branch information
noomorph committed Apr 10, 2024
1 parent 6b5f189 commit 9e5678a
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
20 changes: 20 additions & 0 deletions src/decorator/Bunyamin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,22 @@ describe('Bunyamin', () => {
);
});

test('should process begin-end events', () => {
let counter = 0;
const transformer = jest.fn((fields: any) => {
return { ...fields, index: counter++ };
});

bunyamin.useTransform(transformer);
expect(() => bunyamin.trace.complete('something', willThrow)).toThrow('error');
expect(transformer).toHaveBeenCalledTimes(2);
expect(logger.trace).toHaveBeenCalledWith({ ph: 'B', index: 0 }, 'something');
expect(logger.trace).toHaveBeenCalledWith(
{ ph: 'E', success: false, err: 'error', index: 1 },
'something',
);
});

test('should compose multiple transformation functions', () => {
const context = { cat: 'test' };
const transformer1 = jest.fn((fields: any) => ({ ...fields, x: 3 }));
Expand Down Expand Up @@ -333,3 +349,7 @@ describe('Bunyamin', () => {
error = jest.fn();
}
});

function willThrow() {
throw 'error';
}
6 changes: 3 additions & 3 deletions src/decorator/Bunyamin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ export class Bunyamin<Logger extends BunyanLikeLogger = BunyanLikeLogger> {
): T {
const end = (customContext: EndContext) => {
const endContext = {
...customContext,
...this.#transformContext(customContext),
ph: 'E',
tid: fields.tid,
} as ResolvedFields;
Expand Down Expand Up @@ -194,8 +194,8 @@ export class Bunyamin<Logger extends BunyanLikeLogger = BunyanLikeLogger> {
userContext === undefined
? arguments_
: isError(arguments_[0]) && arguments_.length === 1
? [arguments_[0].message]
: arguments_.slice(1);
? [arguments_[0].message]
: arguments_.slice(1);

return {
fields: this.#resolveFields(fields, phase),
Expand Down
4 changes: 3 additions & 1 deletion src/decorator/types/BunyaminConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@ export type BunyaminConfig<Logger extends BunyanLikeLogger> = {
/**
* Optional transformation of log record fields provided by the user.
*/
transformFields?: <T extends BunyaminLogRecordFields>(context: T | undefined) => T | undefined;
transformFields?: (
fields: BunyaminLogRecordFields | undefined,
) => BunyaminLogRecordFields | undefined;
};

0 comments on commit 9e5678a

Please sign in to comment.