-
Notifications
You must be signed in to change notification settings - Fork 175
Description
Use case
When defining multiple routes related to a specific resource, it's common to have a shared prefix. For example, you might have several routes that all start with /todos
.
For example, if you have a custom domain api.example.com
and you want to map it to the /v1
base path of your API. In this case, all the requests will contain /v1/<resource>
in the path, requiring you to repeat the /v1
prefix in all your route definitions.
To avoid repeating the prefix in each route definition, you can use the prefix
constructor parameter when creating a new Router
instance, and we'll automatically strip it from the request path before matching routes. After mapping a path prefix, the new root path will automatically be mapped to the path argument of /
.
Solution/User Experience
import {
Router,
UnauthorizedError,
} from '@aws-lambda-powertools/event-handler/experimental-rest';
import type { Context } from 'aws-lambda';
const app = new Router({ prefix: '/todos' });
app.post('/', async (_) => { // matches POST /todos
const todos = await getUserTodos();
return { todos };
});
export const handler = async (event: unknown, context: Context) =>
app.resolve(event, context);
This is also useful when splitting routes into separate files (see Split routers section) or when using API mappings{target="_blank"} to map custom domains to specific base paths.
For example, when using prefix: '/pay'
, there is no difference between a request path of /pay
and /pay/
; and the path argument would be defined as /
.
Alternative solutions
Acknowledgment
- This feature request meets Powertools for AWS Lambda (TypeScript) Tenets
- Should this be considered in other Powertools for AWS Lambda languages? i.e. Python, Java, and .NET
Future readers
Please react with 👍 and your use case to help us understand customer demand.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status