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

Add Router proxy with enforced prefix #2

Open
opl- opened this issue Apr 1, 2023 · 0 comments
Open

Add Router proxy with enforced prefix #2

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

Comments

@opl-
Copy link
Owner

opl- commented Apr 1, 2023

A common pattern for me appears to be creating a new Router instance to create a "namespace" of routes. For example, I might create a new Router for all paths starting with /api/user/:userId, on which I will register all endpoints which relate to a specific user: /activity, /posts, /ban (all with the implicit /api/user/:userId prefix). This is done to avoid repetition, and reduce potential for typos or incomplete refactors.

This does work, but makes it more difficult to register middleware (see #1), makes debugging more difficult and possibly increases overhead (the route processing goes through multiple Router handlers), and, if the routes are registered in a different file, makes it more difficult to immediately see what the path prefix is.

A possible pattern to improve this is to introduce a proxy Router, which will always prefix all registered paths with a set prefix.

Exposing this as a Router method would also create a convenient way to expand the context types for all the routes declared under it, for example to introduce the userId param, or a resolved User instance in the state.

const apiRouter = new Router();

interface UserRouterContext {
    params: {
        userId: string;
    };

    state: {
        user: User;
    };
}

// TODO: Function name to be determined (prefix, namespace?).
const userPrefix = apiRouter.createPrefix<{}, UserRouterContext>('/api/user/:userId');

userPrefix.use('/*', async (ctx, next) => {
    const user = await User.byId(ctx.params.userId);
    if (!user) {
        ctx.status = 404;
        return;
    }

    ctx.user = user;

    await next();
});
@opl- opl- added the enhancement New feature or request label Apr 1, 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