Skip to content

Commit

Permalink
feat(RequestLogging): Expose getStore
Browse files Browse the repository at this point in the history
  • Loading branch information
72636c committed Oct 16, 2023
1 parent a641237 commit cd797b6
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/requestLogging/requestLogging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,5 +376,40 @@ describe('RequestLogging', () => {
'x-session-id': '8f859d2a-46a7-4b2d-992b-3da4a18b7ab5',
});
});

it('should allow for mutation via `getStore`', async () => {
const { createContextMiddleware, getStore, 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 mutableFields = getStore();
mutableFields!.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({
abcd: 'extra',
method: 'POST',
url: '/my/test/service',
'x-request-id': expect.any(String),
'x-session-id': '8f859d2a-46a7-4b2d-992b-3da4a18b7ab5',
});
});
});
});
12 changes: 12 additions & 0 deletions src/requestLogging/requestLogging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,18 @@ export const createContextStorage = () => {
async (ctx, next) => {
await loggerContext.run(getFieldsFn(ctx, contextFields(ctx)), next);
},

/**
* Returns the original set of fields from the logger context store.
*
* **Use with caution.** This is only necessary if your application does not
* have all logging fields available when the context middleware is first
* attached to the chain, and needs to append a logging field later in
* request execution.
*
*/
getStore: loggerContext.getStore.bind(loggerContext),

/**
* Returns a shallow copy of fields from the logger context store. For performance reason we only copy the surface level fields.
*/
Expand Down

0 comments on commit cd797b6

Please sign in to comment.