opl- / koa-butterfly

🦋 Butterfly is a feature packed Koa router

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Omitting leading slash seems useful with nested Routers

opl- opened this issue · comments

commented

When nesting Routers, being able to omit the leading slash appears to be useful, specifically in the situation where the user wants to mount something at exact path the nested Router is mounted on:

const router = new Router();
const nestedEntityRouter = new Router();

router.use('/api/entity/:entityId', nestedEntityRouter);

// The two following routes can't be mounted on '/', as it'd effectively enforce the strict slashes Router option, even when not desired.
nestedEntityRouter.use(-10, async (ctx, next) => {
	// Handle querying the resource once, for all routes.
	// Alternatively: enforce access rules for all routes based on the `entityId`.
	ctx.state.entity = await Entity.findById(ctx.params.entityId);

	await next();
});

nestedEntityRouter.get((ctx) => {
	ctx.body = ctx.state.entity.serialize();
});

// Mount nested routers which perform actions on the retrieved entity
nestedEntityRouter.get('/process', (ctx) => {
	ctx.state.entity.performAction(ctx);
});

Obviously, this could be worked around by simply not using a nested router, and instead specifying the full path on all routes.

Arguably, it might also be better for readability to mount the nested Router at '/api/entity', and declare the '/:entityId' parameter on all nested routes. In this instance the existence of entityId was enforced with TypeScript types.

However, another workaround, which I attempted first, is to manually attach the middleware to the nested Router's root node, which turns out to work perfectly fine:

nestedEntityRouter.rootNode.data.getMethodData('GET', true).terminators.addData(/* ... */);

This makes me believe there's no reason not to allow missing leading slashes in the specific instance of mounting at an empty path: .get('', /* ... */).