|
| 1 | +declare const getAllTodos: () => Promise<any[]>; |
| 2 | +declare const putTodo: (body: any) => Promise<any>; |
| 3 | + |
| 4 | +import { |
| 5 | + composeMiddleware, |
| 6 | + Router, |
| 7 | +} from '@aws-lambda-powertools/event-handler/experimental-rest'; |
| 8 | +import type { Middleware } from '@aws-lambda-powertools/event-handler/types'; |
| 9 | +import { Logger } from '@aws-lambda-powertools/logger'; |
| 10 | +import type { Context } from 'aws-lambda'; |
| 11 | + |
| 12 | +const logger = new Logger(); |
| 13 | + |
| 14 | +// Individual middleware functions |
| 15 | +const logging: Middleware = async (params, reqCtx, next) => { |
| 16 | + logger.info(`Request: ${reqCtx.request.method} ${reqCtx.request.url}`); |
| 17 | + await next(); |
| 18 | + logger.info(`Response: ${reqCtx.res.status}`); |
| 19 | +}; |
| 20 | + |
| 21 | +const cors: Middleware = async (params, reqCtx, next) => { |
| 22 | + await next(); |
| 23 | + reqCtx.res.headers.set('Access-Control-Allow-Origin', '*'); |
| 24 | + reqCtx.res.headers.set( |
| 25 | + 'Access-Control-Allow-Methods', |
| 26 | + 'GET, POST, PUT, DELETE' |
| 27 | + ); |
| 28 | +}; |
| 29 | + |
| 30 | +const rateLimit: Middleware = async (params, reqCtx, next) => { |
| 31 | + // Rate limiting logic would go here |
| 32 | + reqCtx.res.headers.set('X-RateLimit-Limit', '100'); |
| 33 | + await next(); |
| 34 | +}; |
| 35 | + |
| 36 | +// Compose middleware stack for all requests |
| 37 | +const apiMiddleware = composeMiddleware([logging, cors, rateLimit]); |
| 38 | + |
| 39 | +const app = new Router(); |
| 40 | + |
| 41 | +// Use composed middleware globally |
| 42 | +app.use(apiMiddleware); |
| 43 | + |
| 44 | +app.get('/todos', async () => { |
| 45 | + const todos = await getAllTodos(); |
| 46 | + return { todos }; |
| 47 | +}); |
| 48 | + |
| 49 | +app.post('/todos', async (params, { request }) => { |
| 50 | + const body = await request.json(); |
| 51 | + const todo = await putTodo(body); |
| 52 | + return todo; |
| 53 | +}); |
| 54 | + |
| 55 | +export const handler = async (event: unknown, context: Context) => { |
| 56 | + return await app.resolve(event, context); |
| 57 | +}; |
0 commit comments