UNPKG

1.68 kBJavaScriptView Raw
1import express from "express";
2import bodyParser from "body-parser";
3import Promise from "bluebird";
4import gatewayApi from "./gateway-api";
5import gatewayAppRouter from "./gateway-app-router";
6import { DEFAULT_GATEWAY_PORT } from "./const";
7
8let server;
9
10
11
12/**
13 * Starts the gateway.
14 * @param apps: The array of applications.
15 * @param options:
16 * - port: The port to use.
17 * - manifest: The manifest to add apps from.
18 */
19const start = (apps, options = {}) => {
20 return new Promise((resolve, reject) => {
21 Promise.coroutine(function*() {
22 const { manifest } = options;
23 const middleware = express().use(bodyParser.json());
24
25 // Retrieve the API route from the manifest.
26 let apiRoute;
27 if (manifest) {
28 if (!manifest.current) { yield manifest.get().catch(err => reject(err)); }
29 apiRoute = manifest.current && manifest.current.api && manifest.current.api.route;
30 }
31
32 // Ensure the gatway is not already running.
33 if (server) {
34 reject(new Error("The gateway server is already running."));
35 }
36
37 // Routes.
38 if (apiRoute) { gatewayApi(apiRoute, apps, middleware, manifest); }
39 gatewayAppRouter(apps, middleware);
40
41 // Listen on the desired port.
42 const port = options.port || DEFAULT_GATEWAY_PORT;
43 server = middleware.listen(port, () => {
44 resolve({ port });
45 });
46 })();
47 });
48 };
49
50
51
52/**
53 * Stops the gateway.
54 */
55const stop = () => {
56 if (server) {
57 server.close();
58 }
59 server = undefined;
60 };
61
62
63
64export default {
65 start,
66 stop,
67 isRunning: () => server !== undefined
68};