@appsemble/node-utils
Version:
NodeJS utilities used by Appsemble internally.
34 lines • 1.05 kB
JavaScript
import { has } from '@appsemble/utils';
import { throwKoaError } from './koa.js';
/**
* A tiny dynamic router middleware for GET requests.
*
* @param routes The routes to serve.
* @returns Middleware that serves middleware matching the route regex.
*/
export function tinyRouter(routes) {
return (ctx, next) => {
const { method, path } = ctx;
let match;
const result = routes.find(({ route }) => {
if (typeof route === 'string') {
return path === route;
}
match = path.match(route) ?? undefined;
return match;
});
if (!result) {
return next();
}
let m = method.toLowerCase();
if (!has(result, m)) {
if (!has(result, 'any')) {
throwKoaError(ctx, 405, 'Method not allowed');
}
m = 'any';
}
ctx.params = match?.groups ? { ...match.groups } : undefined;
return result[m]?.(ctx, next);
};
}
//# sourceMappingURL=tinyRouter.js.map