Linking services together

When using multiple services (or multiple copies of the same service) in thesame database, sometimes you may want to share collections or methods betweenthose services. Typical examples are:

  • collections or APIs for managing shared data(e.g. application users or session data)
  • common middleware that requires someconfiguration that would be identicalfor multiple services
  • reusable routers that provide the same APIfor different servicesFor scenarios like these, Foxx provides a way to link services together andallow them to export JS APIs other services can use.In Foxx these JS APIs are called dependencies,the services implementing them are called providers,the services using them are called consumers.

This chapter is about Foxx dependencies as described above. In JavaScript theterm dependencies can also refer tobundled node modules, which are an unrelated concept.

Declaring dependencies

Foxx dependencies can be declared in theservice manifestusing the provides and dependencies fields:

  • provides lists the dependencies a given service provides,i.e. which APIs it claims to be compatible with

  • dependencies lists the dependencies a given service consumes,i.e. which APIs its dependencies need to be compatible with

Explicitly naming your dependencies helps improving tooling support formanaging service dependencies in ArangoDB but is not strictly necessary.It is possible to omit the provides field even if your service provides aJS API and the dependencies field can be used without explicitly specifyingdependency names.

A dependency name should be an alphanumeric identifier, optionally using anamespace prefix (i.e. dependency-name or @namespace/dependency-name).For example, services maintained by the ArangoDB Foxx team typically usethe @foxx namespace whereas the @arangodb namespaceis reserved for internal use.

There is no official registry for dependency names but we recommend ensuringthe dependency names you use are unambiguous and meaningfulto other developers using your services.

A provides definition maps each provided dependency’s nameto the provided version:

  1. "provides": {
  2. "@example/auth": "1.0.0"
  3. }

A dependencies definition maps the local alias of each consumed dependencyagainst a short definition that includes the name and version range:

  1. "dependencies": {
  2. "myAuth": {
  3. "name": "@example/auth",
  4. "version": "^1.0.0",
  5. "description": "This description is entirely optional.",
  6. "required": false,
  7. "multiple": false
  8. }
  9. }

The local alias should be a valid JavaScript identifier(e.g. a valid variable name). When a dependency has been assigned,its JS API will be exposed in a corresponding property of theservice context,e.g. module.context.dependencies.myAuth.

Assigning dependencies

Like configuration,dependencies can be assigned usingthe web interface,the Foxx CLI orthe Foxx HTTP API.

The value for each dependency should be the database-relative mount path ofthe service (including the leading slash). Both services need to be mounted inthe same database. The same service can be used to provide a dependencyfor multiple services.

Also as with configuration, a service that declares required dependencies whichhave not been assigned will not be mounted by Foxx until all requireddependencies have been assigned. Instead any attempt to access the service’sHTTP API will result in an error code.

Exporting a JS API

In order to provide a JS API other services can consume as a dependency,the service’s main file needs to export something other services can use.You can do this by assigning a value to the module.exports or propertiesof the exports object as with any other module export:

  1. module.exports = "Hello world";

This also includes collections. In the following example, the collectionexported by the provider will use the provider’scollection prefix rather than the consumer’s,allowing both services to share the same collection:

  1. module.exports = module.context.collection("shared_documents");

Let’s imagine we have a service managing our application’s users.Rather than allowing any consuming service to access the collection directly,we can provide a number of methods to manipulate it:

  1. const auth = require("./util/auth");
  2. const users = module.context.collection("users");
  3. exports.login = (username, password) => {
  4. const user = users.firstExample({ username });
  5. if (!user) throw new Error("Wrong username");
  6. const valid = auth.verify(user.authData, password);
  7. if (!valid) throw new Error("Wrong password");
  8. return user;
  9. };
  10. exports.setPassword = (user, password) => {
  11. const authData = auth.create(password);
  12. users.update(user, { authData });
  13. return user;
  14. };

Or you could even export a factory function to create an API that uses acustom error type provided by the consumer rather than the producer:

  1. const auth = require("./util/auth");
  2. const users = module.context.collection("users");
  3. module.exports = (BadCredentialsError = Error) => {
  4. return {
  5. login(username, password) {
  6. const user = users.firstExample({ username });
  7. if (!user) throw new BadCredentialsError("Wrong username");
  8. const valid = auth.verify(user.authData, password);
  9. if (!valid) throw new BadCredentialsError("Wrong password");
  10. return user;
  11. },
  12. setPassword(user, password) {
  13. const authData = auth.create(password);
  14. users.update(user, { authData });
  15. return user;
  16. }
  17. };
  18. };

Example usage (the consumer uses the local alias usersApi):

  1. "use strict";
  2. const createRouter = require("@arangodb/foxx/router");
  3. const joi = require("joi");
  4. // Using the dependency with arguments
  5. const AuthFailureError = require("./errors/auth-failure");
  6. const createUsersApi = module.context.dependencies.usersApi;
  7. const users = createUsersApi(AuthFailureError);
  8. const router = createRouter();
  9. module.context.use(router);
  10. router.use((req, res, next) => {
  11. try {
  12. next();
  13. } catch (e) {
  14. if (e instanceof AuthFailureError) {
  15. res.status(401);
  16. res.json({
  17. error: true,
  18. message: e.message
  19. });
  20. } else {
  21. console.error(e.stack);
  22. res.status(500);
  23. res.json({
  24. error: true,
  25. message: "Something went wrong."
  26. });
  27. }
  28. }
  29. });
  30. router
  31. .post("/login", (req, res) => {
  32. const { username, password } = req.body;
  33. const user = users.login(username, password);
  34. // handle login success
  35. res.json({ welcome: username });
  36. })
  37. .body(
  38. joi.object().keys({
  39. username: joi.string().required(),
  40. password: joi.string().required()
  41. })
  42. );