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:
const usersRouter = require("./api/users");
module.context.use("/users", usersRouter);
// in api/users/index.js
const createRouter = require("@arangodb/foxx/router");
const usersRouter = createRouter();
module.exports = usersRouter;
usersRouter.get("/me", (req, res) => {
// this will be exposed as /users/me
});
Note that you can also mount several routers with the same prefix or even without a prefix:
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:
const createUsersRouter = require("../util/users-router");
const usersRouter = createUsersRouter(
module.context.collection("users"),
"username"
);
module.context.use(usersRouter);
// in util/users-router.js
const createRouter = require("@arangodb/foxx/router");
const { query } = require("@arangodb");
module.export = (usersCollection, keyField) => {
const router = createRouter();
if (!req.session || !req.session.uid) {
res.throw("unauthorized");
}
});
router.get("/me", (req, res) => {
const user = query`
FOR user IN ${usersCollection}
FILTER user[${keyField}] == ${req.session.uid}
LIMIT 1
RETURN user
`.next();
res.json(user);
});
};