Working with routers

    Instead of mounting routers where they are defined, routers can also be exported from one module and imported in another. This allows you to structure your routes by splitting them across multiple files:

    1. const usersRouter = require("./api/users");
    2. module.context.use("/users", usersRouter);
    3. // in api/users/index.js
    4. const createRouter = require("@arangodb/foxx/router");
    5. const usersRouter = createRouter();
    6. module.exports = usersRouter;
    7. usersRouter.get("/me", (req, res) => {
    8. // this will be exposed as /users/me
    9. });

    Note that you can also mount several routers with the same prefix or even without a prefix:

    1. adminRouter.use(groupsAdminRouter);

    This can be especially useful when restricting access to some routes but not others:

    Router factories

    In these cases it can be useful to return the router from a function that takes these differences as arguments instead of exporting the router directly:

    1. const createUsersRouter = require("../util/users-router");
    2. const usersRouter = createUsersRouter(
    3. module.context.collection("users"),
    4. "username"
    5. );
    6. module.context.use(usersRouter);
    7. // in util/users-router.js
    8. const createRouter = require("@arangodb/foxx/router");
    9. const { query } = require("@arangodb");
    10. module.export = (usersCollection, keyField) => {
    11. const router = createRouter();
    12. if (!req.session || !req.session.uid) {
    13. res.throw("unauthorized");
    14. }
    15. });
    16. router.get("/me", (req, res) => {
    17. const user = query`
    18. FOR user IN ${usersCollection}
    19. FILTER user[${keyField}] == ${req.session.uid}
    20. LIMIT 1
    21. RETURN user
    22. `.next();
    23. res.json(user);
    24. });
    25. };