Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions packages/event-handler/src/rest/Router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,9 @@ class Router {
*
* @example
* ```typescript
* const authMiddleware: Middleware = async (params, reqCtx, next) => {
* const authMiddleware: Middleware = async ({params, reqCtx, next}) => {
* // Authentication logic
* if (!isAuthenticated(reqCtx.request)) {
* if (!isAuthenticated(reqCtx.req)) {
* return new Response('Unauthorized', { status: 401 });
* }
* await next();
Expand Down Expand Up @@ -215,23 +215,27 @@ class Router {
};
}

const request = proxyEventToWebRequest(event);
const req = proxyEventToWebRequest(event);

const requestContext: RequestContext = {
event,
context,
request,
req,
// this response should be overwritten by the handler, if it isn't
// it means something went wrong with the middleware chain
res: new Response('', { status: 500 }),
};

try {
const path = new URL(request.url).pathname as Path;
const path = new URL(req.url).pathname as Path;

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

const handlerMiddleware: Middleware = async (params, reqCtx, next) => {
const handlerMiddleware: Middleware = async ({
params,
reqCtx,
next,
}) => {
if (route === null) {
const notFoundRes = await this.handleError(
new NotFoundError(`Route ${path} for method ${method} not found`),
Expand Down Expand Up @@ -263,11 +267,11 @@ class Router {
handlerMiddleware,
]);

const middlewareResult = await middleware(
route?.params ?? {},
requestContext,
() => Promise.resolve()
);
const middlewareResult = await middleware({
params: route?.params ?? {},
reqCtx: requestContext,
next: () => Promise.resolve(),
});

// middleware result takes precedence to allow short-circuiting
const result = middlewareResult ?? requestContext.res;
Expand Down
6 changes: 2 additions & 4 deletions packages/event-handler/src/rest/middleware/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,10 @@ const compress = (options?: CompressionOptions): Middleware => {
const threshold =
options?.threshold ?? DEFAULT_COMPRESSION_RESPONSE_THRESHOLD;

return async (_, reqCtx, next) => {
return async ({ reqCtx, next }) => {
await next();

if (
!shouldCompress(reqCtx.request, reqCtx.res, preferredEncoding, threshold)
) {
if (!shouldCompress(reqCtx.req, reqCtx.res, preferredEncoding, threshold)) {
return;
}

Expand Down
8 changes: 4 additions & 4 deletions packages/event-handler/src/rest/middleware/cors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,16 @@ export const cors = (options?: CorsOptions): Middleware => {
}
};

return async (_params, reqCtx, next) => {
const requestOrigin = reqCtx.request.headers.get('Origin');
return async ({ reqCtx, next }) => {
const requestOrigin = reqCtx.req.headers.get('Origin');
if (!isOriginAllowed(requestOrigin)) {
await next();
return;
}

// Handle preflight OPTIONS request
if (reqCtx.request.method === HttpVerbs.OPTIONS) {
if (!isValidPreflightRequest(reqCtx.request.headers)) {
if (reqCtx.req.method === HttpVerbs.OPTIONS) {
if (!isValidPreflightRequest(reqCtx.req.headers)) {
await next();
return;
}
Expand Down
16 changes: 8 additions & 8 deletions packages/event-handler/src/rest/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,13 @@ export const isAPIGatewayProxyResult = (
*
* @example
* ```typescript
* const middleware1: Middleware = async (params, options, next) => {
* const middleware1: Middleware = async ({params, options, next}) => {
* console.log('middleware1 start');
* await next();
* console.log('middleware1 end');
* };
*
* const middleware2: Middleware = async (params, options, next) => {
* const middleware2: Middleware = async ({params, options, next}) => {
* console.log('middleware2 start');
* await next();
* console.log('middleware2 end');
Expand All @@ -151,11 +151,7 @@ export const isAPIGatewayProxyResult = (
* ```
*/
export const composeMiddleware = (middleware: Middleware[]): Middleware => {
return async (
params: Record<string, string>,
reqCtx: RequestContext,
next: () => Promise<HandlerResponse | void>
): Promise<HandlerResponse | void> => {
return async ({ params, reqCtx, next }): Promise<HandlerResponse | void> => {
let index = -1;
let result: HandlerResponse | undefined;

Expand All @@ -181,7 +177,11 @@ export const composeMiddleware = (middleware: Middleware[]): Middleware => {
return result;
};

const middlewareResult = await middlewareFn(params, reqCtx, nextFn);
const middlewareResult = await middlewareFn({
params,
reqCtx,
next: nextFn,
});

if (nextPromise && !nextAwaited && i < middleware.length - 1) {
throw new Error(
Expand Down
12 changes: 6 additions & 6 deletions packages/event-handler/src/types/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type ErrorResponse = {
};

type RequestContext = {
request: Request;
req: Request;
event: APIGatewayProxyEvent;
context: Context;
res: Response;
Expand Down Expand Up @@ -86,11 +86,11 @@ type RestRouteOptions = {

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

type Middleware = (
params: Record<string, string>,
reqCtx: RequestContext,
next: NextFunction
) => Promise<void | HandlerResponse>;
type Middleware = (args: {
params: Record<string, string>;
reqCtx: RequestContext;
next: NextFunction;
}) => Promise<void | HandlerResponse>;

type RouteRegistryOptions = {
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ describe('Class: Router - Basic Routing', () => {

app.get('/test', async (_params, reqCtx) => {
return {
hasRequest: reqCtx.request instanceof Request,
hasRequest: reqCtx.req instanceof Request,
hasEvent: reqCtx.event === testEvent,
hasContext: reqCtx.context === context,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ describe('Class: Router - Decorators', () => {
@app.get('/test')
public async getTest(_params: any, reqCtx: any) {
return {
hasRequest: reqCtx.request instanceof Request,
hasRequest: reqCtx.req instanceof Request,
hasEvent: reqCtx.event === testEvent,
hasContext: reqCtx.context === context,
};
Expand Down Expand Up @@ -435,7 +435,7 @@ describe('Class: Router - Decorators', () => {
statusCode: HttpErrorCodes.BAD_REQUEST,
error: 'Bad Request',
message: error.message,
hasRequest: reqCtx.request instanceof Request,
hasRequest: reqCtx.req instanceof Request,
hasEvent: reqCtx.event === testEvent,
hasContext: reqCtx.context === context,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ describe('Class: Router - Error Handling', () => {
statusCode: HttpErrorCodes.BAD_REQUEST,
error: 'Bad Request',
message: error.message,
hasRequest: reqCtx.request instanceof Request,
hasRequest: reqCtx.req instanceof Request,
hasEvent: reqCtx.event === testEvent,
hasContext: reqCtx.context === context,
}));
Expand Down
37 changes: 19 additions & 18 deletions packages/event-handler/tests/unit/rest/Router/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,17 @@ describe('Class: Router - Middleware', () => {
const app = new Router();
const executionOrder: string[] = [];

app.use(async (_params, _reqCtx, next) => {
app.use(async ({ next }) => {
executionOrder.push('global-middleware');
await next();
});

const middleware: Middleware[] = middlewareNames.map(
(name) => async (_params, _reqCtx, next) => {
executionOrder.push(name);
await next();
}
(name) =>
async ({ next }) => {
executionOrder.push(name);
await next();
}
);

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

app.use(async (params, reqCtx, next) => {
app.use(async ({ params, reqCtx, next }) => {
middlewareParams = params;
middlewareOptions = reqCtx;
await next();
Expand All @@ -153,15 +154,15 @@ describe('Class: Router - Middleware', () => {
expect(middlewareParams).toEqual({ id: '123' });
expect(middlewareOptions?.event).toBe(testEvent);
expect(middlewareOptions?.context).toBe(context);
expect(middlewareOptions?.request).toBeInstanceOf(Request);
expect(middlewareOptions?.req).toBeInstanceOf(Request);
});

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

app.use(async (_params, _reqCtx, next) => {
app.use(async ({ next }) => {
await next();
await next();
});
Expand All @@ -185,11 +186,11 @@ describe('Class: Router - Middleware', () => {
vi.stubEnv('POWERTOOLS_DEV', 'true');
const app = new Router();

app.use(async (_params, _reqCtx, next) => {
app.use(async ({ next }) => {
await next();
});

app.use(async (_params, _reqCtx, next) => {
app.use(async ({ next }) => {
next();
});

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

app.use(async (_params, _reqCtx, next) => {
app.use(async ({ next }) => {
executionOrder.push('middleware1-start');
await next();
executionOrder.push('middleware1-end');
Expand Down Expand Up @@ -362,7 +363,7 @@ describe('Class: Router - Middleware', () => {
// Prepare
const app = new Router();

app.use(async (_params, reqCtx, next) => {
app.use(async ({ reqCtx, next }) => {
await next();
reqCtx.res.headers.set('x-custom-header', 'middleware-value');
reqCtx.res.headers.set('x-request-id', '12345');
Expand Down Expand Up @@ -393,7 +394,7 @@ describe('Class: Router - Middleware', () => {
// Prepare
const app = new Router();

app.use(async (_params, reqCtx, next) => {
app.use(async ({ reqCtx, next }) => {
await next();
const originalBody = await reqCtx.res.text();
reqCtx.res = new Response(`Modified: ${originalBody}`, {
Expand Down Expand Up @@ -422,7 +423,7 @@ describe('Class: Router - Middleware', () => {
// Prepare
const app = new Router();

app.use(async (_params, reqCtx, next) => {
app.use(async ({ reqCtx, next }) => {
reqCtx.res.headers.set('x-before-handler', 'middleware-value');
await next();
});
Expand Down Expand Up @@ -451,7 +452,7 @@ describe('Class: Router - Middleware', () => {
// Prepare
const app = new Router();

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

app.use(async (_params, reqCtx, next) => {
app.use(async ({ reqCtx, next }) => {
reqCtx.res.headers.set('x-test-header', 'before-next');
await next();
});

app.use(async (_params, reqCtx, next) => {
app.use(async ({ reqCtx, next }) => {
await next();
reqCtx.res.headers.set('x-test-header', 'after-next');
});
Expand Down Expand Up @@ -531,7 +532,7 @@ describe('Class: Router - Middleware', () => {
const app = new Router();
const executionOrder: string[] = [];

app.use(async (_params, _reqCtx, next) => {
app.use(async ({ next }) => {
executionOrder.push('middleware-start');
await next();
executionOrder.push('middleware-end');
Expand Down
18 changes: 9 additions & 9 deletions packages/event-handler/tests/unit/rest/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const createTrackingMiddleware = (
name: string,
executionOrder: string[]
): Middleware => {
return async (_params, _options, next) => {
return async ({ next }) => {
executionOrder.push(`${name}-start`);
await next();
executionOrder.push(`${name}-end`);
Expand All @@ -40,7 +40,7 @@ export const createThrowingMiddleware = (
executionOrder: string[],
errorMessage: string
): Middleware => {
return async (_params, _options, _next) => {
return async () => {
executionOrder.push(name);
throw new Error(errorMessage);
};
Expand All @@ -51,7 +51,7 @@ export const createReturningMiddleware = (
executionOrder: string[],
response: any
): Middleware => {
return async (_params, _options, _next) => {
return async () => {
executionOrder.push(name);
return response;
};
Expand All @@ -61,7 +61,7 @@ export const createNoNextMiddleware = (
name: string,
executionOrder: string[]
): Middleware => {
return async (_params, _options, _next) => {
return async () => {
executionOrder.push(name);
// Intentionally doesn't call next()
};
Expand All @@ -70,21 +70,21 @@ export const createNoNextMiddleware = (
export const createSettingHeadersMiddleware = (headers: {
[key: string]: string;
}): Middleware => {
return async (_params, options, next) => {
return async ({ reqCtx, next }) => {
await next();
Object.entries(headers).forEach(([key, value]) => {
options.res.headers.set(key, value);
reqCtx.res.headers.set(key, value);
});
};
};

export const createHeaderCheckMiddleware = (headers: {
[key: string]: string;
}): Middleware => {
return async (_params, options, next) => {
options.res.headers.forEach((value, key) => {
return async ({ reqCtx, next }) => {
reqCtx.res.headers.forEach((value, key) => {
headers[key] = value;
});
await next();
};
};
};
Loading
Loading