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
15 changes: 15 additions & 0 deletions packages/event-handler/src/rest/ErrorHandlerRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,19 @@ export class ErrorHandlerRegistry {

return null;
}

/**
* Merges another {@link ErrorHandlerRegistry | `ErrorHandlerRegistry`} instance into the current instance.
* It takes the handlers from the provided registry and adds them to the current registry.
*
* @param errorHandlerRegistry - The registry instance to merge with the current instance
*/
public merge(errorHandlerRegistry: ErrorHandlerRegistry): void {
for (const [
errorConstructor,
errorHandler,
] of errorHandlerRegistry.#handlers) {
this.register(errorConstructor, errorHandler);
}
}
}
36 changes: 35 additions & 1 deletion packages/event-handler/src/rest/RouteHandlerRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
ValidationResult,
} from '../types/rest.js';
import { ParameterValidationError } from './errors.js';
import type { Route } from './Route.js';
import { Route } from './Route.js';
import { compilePath, validatePathPattern } from './utils.js';

class RouteHandlerRegistry {
Expand Down Expand Up @@ -193,6 +193,40 @@ class RouteHandlerRegistry {

return null;
}

/**
* Merges another {@link RouteHandlerRegistry | `RouteHandlerRegistry`} instance into the current instance.
* It takes the static and dynamic routes from the provided registry and adds them to the current registry.
*
* @param routeHandlerRegistry - The registry instance to merge with the current instance
* @param options.prefix - An optional prefix to be added to the paths defined in the router
*/
public merge(
routeHandlerRegistry: RouteHandlerRegistry,
options?: { prefix: Path }
): void {
const routes = [
...routeHandlerRegistry.#staticRoutes.values(),
...routeHandlerRegistry.#dynamicRoutes,
];
for (const route of routes) {
let path = route.path;
if (options?.prefix) {
path =
route.path === '/'
? options.prefix
: `${options.prefix}${route.path}`;
}
this.register(
new Route(
route.method as HttpMethod,
path,
route.handler,
route.middleware
)
);
}
}
}

export { RouteHandlerRegistry };
37 changes: 37 additions & 0 deletions packages/event-handler/src/rest/Router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,43 @@ class Router {
handler
);
}

/**
* Merges the routes, context and middleware from the passed router instance into this router instance
*
* @example
* ```typescript
* import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest';
*
* const todosRouter = new Router();
*
* todosRouter.get('/todos', async () => {
* // List API
* });
*
* todosRouter.get('/todos/{todoId}', async () => {
* // Get API
* });
*
* const app = new Router();
* app.includeRouter(todosRouter);
*
* export const handler = async (event: unknown, context: Context) => {
* return app.resolve(event, context);
* };
* ```
* @param router - The Router from which to merge the routes, context and middleware
* @param options.prefix - An optional prefix to be added to the paths defined in the router
*/
public includeRouter(router: Router, options?: { prefix: Path }): void {
this.context = {
...this.context,
...router.context,
};
this.routeRegistry.merge(router.routeRegistry, options);
this.errorHandlerRegistry.merge(router.errorHandlerRegistry);
this.middleware.push(...router.middleware);
}
}

export { Router };
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,47 @@ describe('Class: Router - Basic Routing', () => {
expect(JSON.parse(createResult.body).actualPath).toBe('/todos');
expect(JSON.parse(getResult.body).actualPath).toBe('/todos/1');
});

it('routes to the included router when using split routers', async () => {
// Prepare
const baseRouter = new Router();
baseRouter.get('/', async () => ({ api: 'root' }));
baseRouter.get('/version', async () => ({ api: 'listVersions' }));
baseRouter.get('/version/:id', async () => ({ api: 'getVersion' }));
baseRouter.notFound(async () => ({ error: 'NotFound' }));

const todoRouter = new Router();
todoRouter.get('/', async () => ({ api: 'listTodos' }));
todoRouter.post('/create', async () => ({ api: 'createTodo' }));
todoRouter.get('/:id', async () => ({ api: 'getTodo' }));

const taskRouter = new Router();
taskRouter.get('/', async () => ({ api: 'listTasks' }));
taskRouter.post('/create', async () => ({ api: 'createTask' }));
taskRouter.get('/:taskId', async () => ({ api: 'getTask' }));

const app = new Router();
app.includeRouter(baseRouter);
app.includeRouter(todoRouter, { prefix: '/todos' });
app.includeRouter(taskRouter, { prefix: '/todos/:id/tasks' });

// Act & Assess
const testCases = [
['/', 'GET', 'api', 'root'],
['/version', 'GET', 'api', 'listVersions'],
['/version/1', 'GET', 'api', 'getVersion'],
['/todos', 'GET', 'api', 'listTodos'],
['/todos/create', 'POST', 'api', 'createTodo'],
['/todos/1', 'GET', 'api', 'getTodo'],
['/todos/1/tasks', 'GET', 'api', 'listTasks'],
['/todos/1/tasks/create', 'POST', 'api', 'createTask'],
['/todos/1/tasks/1', 'GET', 'api', 'getTask'],
['/non-existent', 'GET', 'error', 'NotFound'],
] as const;

for (const [path, method, key, expected] of testCases) {
const result = await app.resolve(createTestEvent(path, method), context);
expect(JSON.parse(result.body)[key]).toBe(expected);
}
});
});