UNPKG

2.3 kBJavaScriptView Raw
1import Promise from "bluebird";
2import gateway from "./gateway";
3import log from "./log";
4import pm2 from "./pm2";
5import { promises, sortAppsByRoute } from "./util";
6import { DEFAULT_GATEWAY_PORT } from "./const";
7
8
9
10
11/**
12 * Starts the gateway and all registered apps.
13 * @param apps: Collection of apps to start.
14 * @param update: Function that invokes the update method.
15 * @param apiRoute: The route to explose the API on.
16 * @param manifest: A manifest object.
17 * @param options
18 * - port: The port to start the gateway on.
19 * @return {Promise}
20 */
21export default (apps, update, apiRoute, manifest, options = {}) => {
22 return new Promise((resolve, reject) => {
23 Promise.coroutine(function*() {
24 // Setup initial conditions.
25 log.info("Starting...");
26 log.info("");
27 const GATEWAY_PORT = options.port === undefined ? DEFAULT_GATEWAY_PORT : options.port;
28
29 // Add apps from the manifest.
30 if (manifest) {
31 yield manifest.update().catch(err => reject(err));
32 }
33
34 if (apps.length === 0) {
35 log.warn("WARNING: No apps have been registered. Make sure a manifest has been set.");
36
37 } else {
38 // Kill all apps running in a PM2 process.
39 yield pm2.connect();
40 const processes = yield pm2.apps();
41 if (processes.length > 0) {
42 yield promises(processes.map(item => pm2.delete(item.name)));
43 }
44
45 // Start the gateway and each app.
46 apps = sortAppsByRoute(apps);
47 yield gateway.start(apps, { port: GATEWAY_PORT, apiRoute, manifest }).catch(err => reject(err));
48 const { results: items } = yield promises(apps.map(app => app.start().catch(err => reject(err))));
49
50 // Log status.
51 log.info("");
52 log.info(`Environment: ${ process.env.NODE_ENV || "development" }`);
53 log.info(`Gateway running on port:${ GATEWAY_PORT }`);
54 log.info("");
55 items.forEach(item => {
56 const version = item.version ? ` (v${ item.version })` : "";
57 log.info(` - '${ item.id }'${ version } routing '${ item.route }' => port:${ item.port }`);
58 });
59 log.info("");
60
61 // Ensure all apps are up-to-date.
62 yield update({ start: true });
63
64 // Finish up.
65 resolve({});
66 }
67 })();
68 });
69};