Skip to content

Commit

Permalink
fix(RequestLogging.createContextStorage): Shallow copy context store …
Browse files Browse the repository at this point in the history
…for the `mixin` function (#155)
  • Loading branch information
samchungy authored May 27, 2022
1 parent 22c2ebd commit 733cbd5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
33 changes: 33 additions & 0 deletions src/requestLogging/requestLogging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,5 +341,38 @@ describe('RequestLogging', () => {
'x-session-id': '8f859d2a-46a7-4b2d-992b-3da4a18b7ab5',
});
});

it('should not mutate the current context if surface level fields are changed', async () => {
const { createContextMiddleware, mixin } = createContextStorage();

const contextMiddleware = createContextMiddleware();

// We need to grab the result from within the run() chain
let result: Fields = {};
const setResultMiddleware = jest.fn(async (_ctx: Context, next: Next) => {
const tempResult = mixin();
tempResult.abcd = 'extra';
result = mixin();
await next();
});

const handler = jest.fn((ctx: Context) => {
ctx.status = 201;
});

await createAgent(contextMiddleware, setResultMiddleware, handler)
.post('/my/test/service')
.set('Authenticated-User', 'somesercret')
.set('user-agent', 'Safari')
.set('x-session-id', '8f859d2a-46a7-4b2d-992b-3da4a18b7ab5')
.expect(201);

expect(result).toStrictEqual({
method: 'POST',
url: '/my/test/service',
'x-request-id': expect.any(String),
'x-session-id': '8f859d2a-46a7-4b2d-992b-3da4a18b7ab5',
});
});
});
});
4 changes: 2 additions & 2 deletions src/requestLogging/requestLogging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,8 @@ export const createContextStorage = () => {
await loggerContext.run(getFieldsFn(ctx, contextFields(ctx)), next);
},
/**
* Returns fields from the logger context store
* Returns a shallow copy of fields from the logger context store. For performance reason we only copy the surface level fields.
*/
mixin: () => loggerContext.getStore() ?? {},
mixin: () => ({ ...loggerContext.getStore() }),
};
};

0 comments on commit 733cbd5

Please sign in to comment.