From cd797b6c56b50b135c073254375c39c0202fe39c Mon Sep 17 00:00:00 2001 From: Ryan Ling Date: Mon, 16 Oct 2023 14:22:21 +1100 Subject: [PATCH] feat(RequestLogging): Expose `getStore` --- src/requestLogging/requestLogging.test.ts | 35 +++++++++++++++++++++++ src/requestLogging/requestLogging.ts | 12 ++++++++ 2 files changed, 47 insertions(+) diff --git a/src/requestLogging/requestLogging.test.ts b/src/requestLogging/requestLogging.test.ts index 44fae0a..fa45b2c 100644 --- a/src/requestLogging/requestLogging.test.ts +++ b/src/requestLogging/requestLogging.test.ts @@ -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', + }); + }); }); }); diff --git a/src/requestLogging/requestLogging.ts b/src/requestLogging/requestLogging.ts index b5245af..8fc7728 100644 --- a/src/requestLogging/requestLogging.ts +++ b/src/requestLogging/requestLogging.ts @@ -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. */