Skip to content

Commit a05c074

Browse files
authored
improv(event-handler): change the Middleware and RequestContext signatures (#4530)
1 parent 0a16f5e commit a05c074

File tree

11 files changed

+107
-85
lines changed

11 files changed

+107
-85
lines changed

packages/event-handler/src/rest/Router.ts

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,9 @@ class Router {
164164
*
165165
* @example
166166
* ```typescript
167-
* const authMiddleware: Middleware = async (params, reqCtx, next) => {
167+
* const authMiddleware: Middleware = async ({ params, reqCtx, next }) => {
168168
* // Authentication logic
169-
* if (!isAuthenticated(reqCtx.request)) {
169+
* if (!isAuthenticated(reqCtx.req)) {
170170
* return new Response('Unauthorized', { status: 401 });
171171
* }
172172
* await next();
@@ -215,23 +215,27 @@ class Router {
215215
};
216216
}
217217

218-
const request = proxyEventToWebRequest(event);
218+
const req = proxyEventToWebRequest(event);
219219

220220
const requestContext: RequestContext = {
221221
event,
222222
context,
223-
request,
223+
req,
224224
// this response should be overwritten by the handler, if it isn't
225225
// it means something went wrong with the middleware chain
226226
res: new Response('', { status: 500 }),
227227
};
228228

229229
try {
230-
const path = new URL(request.url).pathname as Path;
230+
const path = new URL(req.url).pathname as Path;
231231

232232
const route = this.routeRegistry.resolve(method, path);
233233

234-
const handlerMiddleware: Middleware = async (params, reqCtx, next) => {
234+
const handlerMiddleware: Middleware = async ({
235+
params,
236+
reqCtx,
237+
next,
238+
}) => {
235239
if (route === null) {
236240
const notFoundRes = await this.handleError(
237241
new NotFoundError(`Route ${path} for method ${method} not found`),
@@ -263,11 +267,11 @@ class Router {
263267
handlerMiddleware,
264268
]);
265269

266-
const middlewareResult = await middleware(
267-
route?.params ?? {},
268-
requestContext,
269-
() => Promise.resolve()
270-
);
270+
const middlewareResult = await middleware({
271+
params: route?.params ?? {},
272+
reqCtx: requestContext,
273+
next: () => Promise.resolve(),
274+
});
271275

272276
// middleware result takes precedence to allow short-circuiting
273277
const result = middlewareResult ?? requestContext.res;

packages/event-handler/src/rest/middleware/compress.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,10 @@ const compress = (options?: CompressionOptions): Middleware => {
6767
const threshold =
6868
options?.threshold ?? DEFAULT_COMPRESSION_RESPONSE_THRESHOLD;
6969

70-
return async (_, reqCtx, next) => {
70+
return async ({ reqCtx, next }) => {
7171
await next();
7272

73-
if (
74-
!shouldCompress(reqCtx.request, reqCtx.res, preferredEncoding, threshold)
75-
) {
73+
if (!shouldCompress(reqCtx.req, reqCtx.res, preferredEncoding, threshold)) {
7674
return;
7775
}
7876

packages/event-handler/src/rest/middleware/cors.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,16 +96,16 @@ export const cors = (options?: CorsOptions): Middleware => {
9696
}
9797
};
9898

99-
return async (_params, reqCtx, next) => {
100-
const requestOrigin = reqCtx.request.headers.get('Origin');
99+
return async ({ reqCtx, next }) => {
100+
const requestOrigin = reqCtx.req.headers.get('Origin');
101101
if (!isOriginAllowed(requestOrigin)) {
102102
await next();
103103
return;
104104
}
105105

106106
// Handle preflight OPTIONS request
107-
if (reqCtx.request.method === HttpVerbs.OPTIONS) {
108-
if (!isValidPreflightRequest(reqCtx.request.headers)) {
107+
if (reqCtx.req.method === HttpVerbs.OPTIONS) {
108+
if (!isValidPreflightRequest(reqCtx.req.headers)) {
109109
await next();
110110
return;
111111
}

packages/event-handler/src/rest/utils.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import type {
66
HttpMethod,
77
Middleware,
88
Path,
9-
RequestContext,
109
ValidationResult,
1110
} from '../types/rest.js';
1211
import {
@@ -129,13 +128,13 @@ export const isAPIGatewayProxyResult = (
129128
*
130129
* @example
131130
* ```typescript
132-
* const middleware1: Middleware = async (params, options, next) => {
131+
* const middleware1: Middleware = async ({params, options, next}) => {
133132
* console.log('middleware1 start');
134133
* await next();
135134
* console.log('middleware1 end');
136135
* };
137136
*
138-
* const middleware2: Middleware = async (params, options, next) => {
137+
* const middleware2: Middleware = async ({params, options, next}) => {
139138
* console.log('middleware2 start');
140139
* await next();
141140
* console.log('middleware2 end');
@@ -151,11 +150,7 @@ export const isAPIGatewayProxyResult = (
151150
* ```
152151
*/
153152
export const composeMiddleware = (middleware: Middleware[]): Middleware => {
154-
return async (
155-
params: Record<string, string>,
156-
reqCtx: RequestContext,
157-
next: () => Promise<HandlerResponse | void>
158-
): Promise<HandlerResponse | void> => {
153+
return async ({ params, reqCtx, next }): Promise<HandlerResponse | void> => {
159154
let index = -1;
160155
let result: HandlerResponse | undefined;
161156

@@ -181,7 +176,11 @@ export const composeMiddleware = (middleware: Middleware[]): Middleware => {
181176
return result;
182177
};
183178

184-
const middlewareResult = await middlewareFn(params, reqCtx, nextFn);
179+
const middlewareResult = await middlewareFn({
180+
params,
181+
reqCtx,
182+
next: nextFn,
183+
});
185184

186185
if (nextPromise && !nextAwaited && i < middleware.length - 1) {
187186
throw new Error(

packages/event-handler/src/types/rest.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ type ErrorResponse = {
1515
};
1616

1717
type RequestContext = {
18-
request: Request;
18+
req: Request;
1919
event: APIGatewayProxyEvent;
2020
context: Context;
2121
res: Response;
@@ -86,11 +86,11 @@ type RestRouteOptions = {
8686

8787
type NextFunction = () => Promise<HandlerResponse | void>;
8888

89-
type Middleware = (
90-
params: Record<string, string>,
91-
reqCtx: RequestContext,
92-
next: NextFunction
93-
) => Promise<void | HandlerResponse>;
89+
type Middleware = (args: {
90+
params: Record<string, string>;
91+
reqCtx: RequestContext;
92+
next: NextFunction;
93+
}) => Promise<void | HandlerResponse>;
9494

9595
type RouteRegistryOptions = {
9696
/**

packages/event-handler/tests/unit/rest/Router/basic-routing.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ describe('Class: Router - Basic Routing', () => {
9191

9292
app.get('/test', async (_params, reqCtx) => {
9393
return {
94-
hasRequest: reqCtx.request instanceof Request,
94+
hasRequest: reqCtx.req instanceof Request,
9595
hasEvent: reqCtx.event === testEvent,
9696
hasContext: reqCtx.context === context,
9797
};

packages/event-handler/tests/unit/rest/Router/decorators.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ describe('Class: Router - Decorators', () => {
400400
@app.get('/test')
401401
public async getTest(_params: any, reqCtx: any) {
402402
return {
403-
hasRequest: reqCtx.request instanceof Request,
403+
hasRequest: reqCtx.req instanceof Request,
404404
hasEvent: reqCtx.event === testEvent,
405405
hasContext: reqCtx.context === context,
406406
};
@@ -435,7 +435,7 @@ describe('Class: Router - Decorators', () => {
435435
statusCode: HttpErrorCodes.BAD_REQUEST,
436436
error: 'Bad Request',
437437
message: error.message,
438-
hasRequest: reqCtx.request instanceof Request,
438+
hasRequest: reqCtx.req instanceof Request,
439439
hasEvent: reqCtx.event === testEvent,
440440
hasContext: reqCtx.context === context,
441441
};

packages/event-handler/tests/unit/rest/Router/error-handling.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ describe('Class: Router - Error Handling', () => {
375375
statusCode: HttpErrorCodes.BAD_REQUEST,
376376
error: 'Bad Request',
377377
message: error.message,
378-
hasRequest: reqCtx.request instanceof Request,
378+
hasRequest: reqCtx.req instanceof Request,
379379
hasEvent: reqCtx.event === testEvent,
380380
hasContext: reqCtx.context === context,
381381
}));

packages/event-handler/tests/unit/rest/Router/middleware.test.ts

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,17 @@ describe('Class: Router - Middleware', () => {
4444
const app = new Router();
4545
const executionOrder: string[] = [];
4646

47-
app.use(async (_params, _reqCtx, next) => {
47+
app.use(async ({ next }) => {
4848
executionOrder.push('global-middleware');
4949
await next();
5050
});
5151

5252
const middleware: Middleware[] = middlewareNames.map(
53-
(name) => async (_params, _reqCtx, next) => {
54-
executionOrder.push(name);
55-
await next();
56-
}
53+
(name) =>
54+
async ({ next }) => {
55+
executionOrder.push(name);
56+
await next();
57+
}
5758
);
5859

5960
app.get(path as Path, middleware, async () => {
@@ -137,7 +138,7 @@ describe('Class: Router - Middleware', () => {
137138
let middlewareParams: Record<string, string> | undefined;
138139
let middlewareOptions: RequestContext | undefined;
139140

140-
app.use(async (params, reqCtx, next) => {
141+
app.use(async ({ params, reqCtx, next }) => {
141142
middlewareParams = params;
142143
middlewareOptions = reqCtx;
143144
await next();
@@ -153,15 +154,15 @@ describe('Class: Router - Middleware', () => {
153154
expect(middlewareParams).toEqual({ id: '123' });
154155
expect(middlewareOptions?.event).toBe(testEvent);
155156
expect(middlewareOptions?.context).toBe(context);
156-
expect(middlewareOptions?.request).toBeInstanceOf(Request);
157+
expect(middlewareOptions?.req).toBeInstanceOf(Request);
157158
});
158159

159160
it('returns error response when next() is called multiple times', async () => {
160161
// Prepare
161162
vi.stubEnv('POWERTOOLS_DEV', 'true');
162163
const app = new Router();
163164

164-
app.use(async (_params, _reqCtx, next) => {
165+
app.use(async ({ next }) => {
165166
await next();
166167
await next();
167168
});
@@ -185,11 +186,11 @@ describe('Class: Router - Middleware', () => {
185186
vi.stubEnv('POWERTOOLS_DEV', 'true');
186187
const app = new Router();
187188

188-
app.use(async (_params, _reqCtx, next) => {
189+
app.use(async ({ next }) => {
189190
await next();
190191
});
191192

192-
app.use(async (_params, _reqCtx, next) => {
193+
app.use(async ({ next }) => {
193194
next();
194195
});
195196

@@ -241,7 +242,7 @@ describe('Class: Router - Middleware', () => {
241242
const app = new Router();
242243
const executionOrder: string[] = [];
243244

244-
app.use(async (_params, _reqCtx, next) => {
245+
app.use(async ({ next }) => {
245246
executionOrder.push('middleware1-start');
246247
await next();
247248
executionOrder.push('middleware1-end');
@@ -362,7 +363,7 @@ describe('Class: Router - Middleware', () => {
362363
// Prepare
363364
const app = new Router();
364365

365-
app.use(async (_params, reqCtx, next) => {
366+
app.use(async ({ reqCtx, next }) => {
366367
await next();
367368
reqCtx.res.headers.set('x-custom-header', 'middleware-value');
368369
reqCtx.res.headers.set('x-request-id', '12345');
@@ -393,7 +394,7 @@ describe('Class: Router - Middleware', () => {
393394
// Prepare
394395
const app = new Router();
395396

396-
app.use(async (_params, reqCtx, next) => {
397+
app.use(async ({ reqCtx, next }) => {
397398
await next();
398399
const originalBody = await reqCtx.res.text();
399400
reqCtx.res = new Response(`Modified: ${originalBody}`, {
@@ -422,7 +423,7 @@ describe('Class: Router - Middleware', () => {
422423
// Prepare
423424
const app = new Router();
424425

425-
app.use(async (_params, reqCtx, next) => {
426+
app.use(async ({ reqCtx, next }) => {
426427
reqCtx.res.headers.set('x-before-handler', 'middleware-value');
427428
await next();
428429
});
@@ -451,7 +452,7 @@ describe('Class: Router - Middleware', () => {
451452
// Prepare
452453
const app = new Router();
453454

454-
app.use(async (_params, reqCtx, next) => {
455+
app.use(async ({ reqCtx, next }) => {
455456
reqCtx.res.headers.set('x-before-handler', 'middleware-value');
456457
await next();
457458
});
@@ -478,12 +479,12 @@ describe('Class: Router - Middleware', () => {
478479
// Prepare
479480
const app = new Router();
480481

481-
app.use(async (_params, reqCtx, next) => {
482+
app.use(async ({ reqCtx, next }) => {
482483
reqCtx.res.headers.set('x-test-header', 'before-next');
483484
await next();
484485
});
485486

486-
app.use(async (_params, reqCtx, next) => {
487+
app.use(async ({ reqCtx, next }) => {
487488
await next();
488489
reqCtx.res.headers.set('x-test-header', 'after-next');
489490
});
@@ -531,7 +532,7 @@ describe('Class: Router - Middleware', () => {
531532
const app = new Router();
532533
const executionOrder: string[] = [];
533534

534-
app.use(async (_params, _reqCtx, next) => {
535+
app.use(async ({ next }) => {
535536
executionOrder.push('middleware-start');
536537
await next();
537538
executionOrder.push('middleware-end');

0 commit comments

Comments
 (0)