Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
93 lines (83 loc) · 2.03 KB
/
Copy pathindex.js
File metadata and controls
93 lines (83 loc) · 2.03 KB
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
'use strict';
/**
* Lark Bootstrap
* Initialize an nodejs app / Koa app / Lark app
**/
import extend from 'extend';
import _debug from 'debug';
import pm from './lib/pm';
import DEFAULT_CONFIG from './config/default.json';
const debug = _debug('lark-bootstrap');
const bootstrap = {
config: DEFAULT_CONFIG,
hooks: [],
};
/**
* Configure
**/
let started = false;
bootstrap.configure = (config) => {
if (started) {
throw new Error("Can not configure after bootstrap started!");
}
debug('Bootstrap: configure');
config = extend(true, {}, config);
bootstrap.config = extend(true, bootstrap.config, config);
return bootstrap;
};
/**
* Bootstrap current service
**/
bootstrap.async_start = async () => {
debug('Bootstrap: start in async function');
bootstrap.configure();
started = true;
let state;
if (bootstrap.config.pm && bootstrap.config.pm.enable !== false) {
state = await pm(bootstrap.config.pm);
}
if (state.isMaster) {
process.exit(0);
}
const ctx = {
bootstrap: bootstrap,
config: extend(true, {}, bootstrap.config),
};
if (state) {
ctx.state = extend(true, {}, state);
}
for (let i = 0; i < bootstrap.hooks.length; i++) {
let fn = bootstrap.hooks[i];
await fn(ctx);
}
};
/**
* Bootstrap start, returning a promise
**/
bootstrap.start = () => {
debug('Bootstrap: start');
return new Promise((resolve, reject) => {
(async () => {
try {
await bootstrap.async_start();
}
catch (e) {
return reject(e);
}
return resolve();
})();
});
};
/**
* Add hooks before booting
**/
bootstrap.use = (fn) => {
debug('Bootstrap: use');
if (!(fn instanceof Function)) {
throw new Error('Param for Bootstrap.use must be a Function!');
}
bootstrap.hooks.push(fn);
return bootstrap;
};
export default bootstrap;
debug('Bootstrap: script loaded');