Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Omitting leading slash seems useful with nested Routers #1

Open
opl- opened this issue Feb 26, 2023 · 0 comments
Open

Omitting leading slash seems useful with nested Routers #1

opl- opened this issue Feb 26, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@opl-
Copy link
Owner

opl- commented Feb 26, 2023

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('', /* ... */).

@opl- opl- added the enhancement New feature or request label Feb 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant