1 |
|
2 |
|
3 |
|
4 |
|
5 | const config = require('./src/config');
|
6 | const router = require('./router');
|
7 | const reply = require('./reply');
|
8 | const join = require('./src/join/index.js');
|
9 | const modern = require('./src/modern');
|
10 |
|
11 |
|
12 | const context = (self, req, res) => Object.assign(req, self, { req, res });
|
13 |
|
14 |
|
15 | const hook = (ctx, name) => ctx.plugins.map(p => p[name]).filter(p => p);
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | const Server = async (...middle) => {
|
21 |
|
22 |
|
23 | const ctx = {};
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | const opts = (
|
29 | typeof middle[0] === 'undefined' ||
|
30 | typeof middle[0] === 'boolean' ||
|
31 | typeof middle[0] === 'string' ||
|
32 | middle[0] === null ||
|
33 | middle[0] instanceof Function ||
|
34 | middle[0] instanceof Array
|
35 | ) ? {} : middle.shift();
|
36 |
|
37 |
|
38 | ctx.options = await config(opts, module.exports.plugins);
|
39 |
|
40 |
|
41 | ctx.plugins = module.exports.plugins.filter(p => ctx.options[p.name]);
|
42 |
|
43 | ctx.utils = { modern: modern };
|
44 | ctx.modern = modern;
|
45 |
|
46 |
|
47 | for (let init of hook(ctx, 'init')) {
|
48 | await init(ctx);
|
49 | }
|
50 |
|
51 |
|
52 |
|
53 |
|
54 | ctx.middle = join(hook(ctx, 'before'), middle, hook(ctx, 'after'));
|
55 |
|
56 |
|
57 | ctx.app.use((req, res) => ctx.middle(context(ctx, req, res)));
|
58 |
|
59 |
|
60 |
|
61 |
|
62 | await Promise.all(hook(ctx, 'listen').map(listen => listen(ctx)));
|
63 |
|
64 |
|
65 | for (let launch of hook(ctx, 'launch')) {
|
66 | await launch(ctx);
|
67 | }
|
68 |
|
69 | return ctx;
|
70 | };
|
71 |
|
72 | module.exports = Server;
|
73 | module.exports.router = router;
|
74 | module.exports.reply = reply;
|
75 | module.exports.utils = {
|
76 | modern: modern
|
77 | };
|
78 | module.exports.plugins = [
|
79 | require('./plugins/log'),
|
80 | require('./plugins/express'),
|
81 | require('./plugins/parser'),
|
82 | require('./plugins/static'),
|
83 | require('./plugins/socket'),
|
84 | require('./plugins/session'),
|
85 | require('./plugins/security'),
|
86 | require('./plugins/favicon'),
|
87 | require('./plugins/compress'),
|
88 | require('./plugins/final')
|
89 | ];
|