|
7 | 7 | ContextExamples as dummyContext,
|
8 | 8 | Events as dummyEvent,
|
9 | 9 | } from '@aws-lambda-powertools/commons';
|
| 10 | +import { cleanupMiddlewares } from '@aws-lambda-powertools/commons/lib/middleware'; |
10 | 11 | import {
|
11 | 12 | ConfigServiceInterface,
|
12 | 13 | EnvironmentVariablesService,
|
@@ -197,6 +198,64 @@ describe('Middy middleware', () => {
|
197 | 198 | persistentAttribsBeforeInvocation
|
198 | 199 | );
|
199 | 200 | });
|
| 201 | + |
| 202 | + test('when enabled, and another middleware returns early, it still clears the state', async () => { |
| 203 | + // Prepare |
| 204 | + const logger = new Logger({ |
| 205 | + logLevel: 'DEBUG', |
| 206 | + }); |
| 207 | + const loggerSpy = jest.spyOn(logger['console'], 'debug'); |
| 208 | + const myCustomMiddleware = (): middy.MiddlewareObj => { |
| 209 | + const before = async ( |
| 210 | + request: middy.Request |
| 211 | + ): Promise<undefined | string> => { |
| 212 | + // Return early on the second invocation |
| 213 | + if (request.event.idx === 1) { |
| 214 | + // Cleanup Powertools resources |
| 215 | + await cleanupMiddlewares(request); |
| 216 | + |
| 217 | + // Then return early |
| 218 | + return 'foo'; |
| 219 | + } |
| 220 | + }; |
| 221 | + |
| 222 | + return { |
| 223 | + before, |
| 224 | + }; |
| 225 | + }; |
| 226 | + const handler = middy( |
| 227 | + ( |
| 228 | + event: typeof dummyEvent.Custom.CustomEvent & { idx: number } |
| 229 | + ): void => { |
| 230 | + // Add a key only at the first invocation, so we can check that it's cleared |
| 231 | + if (event.idx === 0) { |
| 232 | + logger.appendKeys({ |
| 233 | + details: { user_id: '1234' }, |
| 234 | + }); |
| 235 | + } |
| 236 | + logger.debug('This is a DEBUG log'); |
| 237 | + } |
| 238 | + ) |
| 239 | + .use(injectLambdaContext(logger, { clearState: true })) |
| 240 | + .use(myCustomMiddleware()); |
| 241 | + |
| 242 | + // Act |
| 243 | + await handler({ ...event, idx: 0 }, context); |
| 244 | + await handler({ ...event, idx: 1 }, context); |
| 245 | + |
| 246 | + // Assess |
| 247 | + const persistentAttribsAfterInvocation = { |
| 248 | + ...logger.getPersistentLogAttributes(), |
| 249 | + }; |
| 250 | + expect(persistentAttribsAfterInvocation).toEqual({}); |
| 251 | + // Only one log because the second invocation returned early |
| 252 | + // from the custom middleware |
| 253 | + expect(loggerSpy).toBeCalledTimes(1); |
| 254 | + expect(loggerSpy).toHaveBeenNthCalledWith( |
| 255 | + 1, |
| 256 | + expect.stringContaining('"details":{"user_id":"1234"}') |
| 257 | + ); |
| 258 | + }); |
200 | 259 | });
|
201 | 260 |
|
202 | 261 | describe('Feature: log event', () => {
|
|
0 commit comments