This repository has been archived by the owner on Jul 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
83 lines (69 loc) · 2.31 KB
/
app.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
const EventEmitter = require("events");
const architect = require("architect");
const debug = require("debug");
const chalk = require("chalk");
const lodash = require("lodash");
const path = require("path");
const expr = require("./utils/expressions");
const packageJSON = require("./package.json");
const CORE_CONFIG_PATH = path.join(__dirname, "conf.js");
const EVENTS = {
APPLICATION_READY: "APPLICATION:READY",
APPLICATION_SHUTDOWN: "APPLICATION:SHUTDOWN",
SERVICE_REGISTERED: "SERVICE:REGISTERED",
PLUGIN_REGISTERED: "PLUGIN:REGISTERED"
};
let shutdownWasCalled = false;
const log = debug(`${packageJSON.name}:app`);
const shutdown = function() {
expr.whenFalse(shutdownWasCalled, () => {
shutdownWasCalled = true;
let counter = this.listeners(EVENTS.APPLICATION_SHUTDOWN).length;
expr.whenTrue(counter === 0, process.exit.bind(process, 0));
// count the handlers , and when handler call next, augment +1 counter
// when counter is equal to the handler , close in a 'sign kill'
this.emit(EVENTS.APPLICATION_SHUTDOWN, () => {
counter--;
if (counter <= 0) {
// kill process in a sigterm
process.exit(1);
}
});
});
};
class App extends EventEmitter {
get events() {
return EVENTS;
}
constructor() {
super();
this.services = null;
const bindedShutdown = shutdown.bind(this);
process.on("SIGINT", bindedShutdown);
process.on("SIGTERM", bindedShutdown);
}
start(configPath) {
// creating built in core plugins config
const coreConfig = architect.loadConfig(CORE_CONFIG_PATH);
// creating client config
const clientConfig = architect.loadConfig(configPath);
const config = [...coreConfig, ...clientConfig];
architect.createApp(config, (err, app) => {
if (err) {
log(chalk.red("Was an error creating architect pipe flow app"));
log(err);
throw err;
}
app.on("service", this.emit.bind(this, EVENTS.SERVICE_REGISTERED));
app.on("plugin", this.emit.bind(this, EVENTS.PLUGIN_REGISTERED));
// set services to provide using app.service
this.services = app.services;
log(chalk.green("Sherminator is ready :)"));
this.emit(EVENTS.APPLICATION_READY);
});
}
service(pattern) {
return lodash.get(this.services, pattern);
}
}
module.exports = App;