summaryrefslogtreecommitdiff
path: root/src/app/services/index.js
blob: ea0175d0065f1cb592831da0bc252556a470a796 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
 * Configure services and mount them.
 * @module app/services/index
 */

import AuthenticationService from "app/services/authentication";
import ShoeService from "app/services/shoe";

import configureDatabase from "app/db/configure";

/**
 * A cache of registered services
 * @type {Object}
 */
const services = {};

/**
 * Function to get a service by resource name
 * @param {String} resourceName  name of the service to fetch
 */
function get(resourceName) {
  return services[resourceName];
}

/**
 * List services
 * @return {object}  the services object
 */
function list() {
  return Object.entries(services);
}

/**
 * Configure the API endpoints
 * @param {Express} app   Express application
 * @param {Knex}    knex  Knex instance (optional)
 */
async function configure(app, knex) {
  const { bookshelf } = configureDatabase(knex);

  /**
   * Connect a service
   * @param  {Service} RoutableService  the service to connect
   * @return {express.Router}           the service's router
   */
  async function connect(RoutableService) {
    const service = await RoutableService(bookshelf);
    services[service.resource] = service;
    return service.router;
  }

  app.use("/api/v1/auth", await connect(AuthenticationService));
  app.use("/api/v1/shoe", await connect(ShoeService));

  app.get("/api/v1/", describeApplication);
  // app.get("/", describeApplication);
}

/**
 * Canary middleware to indicate that the API is working
 */
function describeApplication(request, response) {
  response.json({ application: "Shoebox" });
}

export default {
  configure,
  get,
  list,
};