-
Notifications
You must be signed in to change notification settings - Fork 70
/
index.js
226 lines (199 loc) · 5.54 KB
/
index.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/*eslint no-process-env: 0, no-console: 0 */
const merge = require('lodash.merge')
const EventEmitter = require('events').EventEmitter
const lib = require('./lib')
// inject Error and Resource types into the global namespace
lib.Core.assignGlobals()
/**
* The Trails Application. Merges the configuration and API resources
* loads Trailpacks, initializes logging and event listeners.
*/
module.exports = class TrailsApp extends EventEmitter {
/**
* @param app.api The application api (api/ folder)
* @param app.config The application configuration (config/ folder)
*
* Initialize the Trails Application and its EventEmitter parentclass. Set
* some necessary default configuration.
* @param app config to create Trails instance
*/
constructor(app) {
super()
if (!app) {
throw new RangeError('No app definition provided to Trails constructor')
}
if (!app.pkg) {
throw new PackageNotDefinedError()
}
if (!app.api) {
throw new ApiNotDefinedError()
}
app.api.models || (app.api.models = {})
app.api.services || (app.api.services = {})
app.api.resolvers || (app.api.resolvers = {})
app.api.policies || (app.api.policies = {})
app.api.controllers || (app.api.controllers = {})
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development'
}
const processEnv = Object.freeze(JSON.parse(JSON.stringify(process.env)))
Object.defineProperties(this, {
logger: {
value: new lib.LoggerProxy(this),
enumerable: false,
writable: false
},
env: {
enumerable: false,
value: processEnv
},
pkg: {
enumerable: false,
value: app.pkg
},
versions: {
enumerable: false,
writable: false,
configurable: false,
value: process.versions
},
api: {
value: app.api,
writable: true,
configurable: true
},
_trails: {
enumerable: false,
value: require('./package')
},
packs: {
value: {}
}
})
let trailpacksConfig = {}
// instantiate trailpacks
if (app.config.main && app.config.main.packs) {
app.config.main.packs.forEach(Pack => {
try {
const pack = new Pack(this)
this.packs[pack.name] = pack
trailpacksConfig = merge(trailpacksConfig, pack.config)
lib.Core.mergeApi(this, pack)
lib.Core.bindTrailpackMethodListeners(this, pack)
}
catch (e) {
console.log(e.stack)
throw new TrailpackError(Pack, e, 'constructor')
}
})
}
Object.defineProperties(this, {
config: {
value: new lib.Configuration(trailpacksConfig, processEnv),
configurable: true,
writable: false
}
})
this.config.merge(app.config)
const envConfig = app.config.env && app.config.env[processEnv.NODE_ENV]
if (envConfig) {
this.config.merge(envConfig)
}
this.setMaxListeners(this.config.get('main.maxListeners'))
// instantiate resource classes and bind resource methods
this.controllers = lib.Core.bindMethods(this, 'controllers')
this.policies = lib.Core.bindMethods(this, 'policies')
this.services = lib.Core.bindMethods(this, 'services')
this.models = lib.Core.bindMethods(this, 'models')
this.resolvers = lib.Core.bindMethods(this, 'resolvers')
this.emit('trails:configured')
lib.Core.bindApplicationListeners(this)
lib.Core.bindTrailpackPhaseListeners(this, Object.values(this.packs))
}
/**
* Start the App. Load all Trailpacks.
*
* @return Promise
*/
async start() {
this.emit('trails:start')
await this.after('trails:ready')
return this
}
/**
* Shutdown. Unbind listeners, unload trailpacks.
* @return Promise
*/
async stop() {
this.emit('trails:stop')
await Promise
.all(Object.values(this.packs).map(pack => {
this.log.debug('Unloading trailpack', pack.name, '...')
return pack.unload()
}))
.then(() => {
this.log.debug('All trailpacks unloaded. Done.')
this.removeAllListeners()
})
return this
}
/**
* Resolve Promise once ANY of the events in the list have emitted.
*
* @return Promise
*/
async onceAny(events) {
if (!Array.isArray(events)) {
events = [events]
}
let resolveCallback
return Promise
.race(events.map(eventName => {
return new Promise(resolve => {
resolveCallback = resolve
this.once(eventName, resolveCallback)
})
}))
.then((...args) => {
events.forEach(eventName => this.removeListener(eventName, resolveCallback))
return args
})
.catch(err => {
this.log.error(err, 'handling onceAny events', events)
throw err
})
}
/**
* Resolve Promise once all events in the list have emitted. Also accepts
*
* a callback.
* @return Promise
*/
async after(events) {
if (!Array.isArray(events)) {
events = [events]
}
return Promise
.all(events.map(eventName => {
return new Promise(resolve => {
if (eventName instanceof Array) {
resolve(this.onceAny(eventName))
}
else {
this.once(eventName, resolve)
}
})
}))
.catch(err => {
this.log.error(err, 'handling after events', events)
throw err
})
}
/**
* Return the Trails logger
* @fires trails:log:* log events
*/
get log() {
return this.logger
}
}