UNPKG

2.34 kBJavaScriptView Raw
1// server for Node.js (https://serverjs.io/)
2// A simple and powerful server for Node.js.
3
4// Internal modules
5const config = require('./src/config');
6const router = require('./router');
7const reply = require('./reply');
8const join = require('./src/join/index.js');
9const modern = require('./src/modern');
10
11// Create a context per-request
12const context = (self, req, res) => Object.assign(req, self, { req, res });
13
14// Get the functions from the plugins for a special point
15const hook = (ctx, name) => ctx.plugins.map(p => p[name]).filter(p => p);
16
17
18
19// Main function
20const Server = async (...middle) => {
21
22 // Initialize the global context
23 const ctx = {};
24
25 // First parameter can be:
26 // - options: Number || Object (cannot be ID'd)
27 // - middleware: undefined || null || Boolean || Function || Array
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 // Set the options for the context of Server.js
38 ctx.options = await config(opts, module.exports.plugins);
39
40 // Only enabled plugins through the config
41 ctx.plugins = module.exports.plugins.filter(p => ctx.options[p.name]);
42
43 ctx.utils = { modern: modern };
44 ctx.modern = modern;
45
46 // All the init beforehand
47 for (let init of hook(ctx, 'init')) {
48 await init(ctx);
49 }
50
51
52
53 // PLUGIN middleware
54 ctx.middle = join(hook(ctx, 'before'), middle, hook(ctx, 'after'));
55
56 // Main thing here
57 ctx.app.use((req, res) => ctx.middle(context(ctx, req, res)));
58
59
60
61 // Different listening methods
62 await Promise.all(hook(ctx, 'listen').map(listen => listen(ctx)));
63
64 // After launching it (already proxified)
65 for (let launch of hook(ctx, 'launch')) {
66 await launch(ctx);
67 }
68
69 return ctx;
70};
71
72module.exports = Server;
73module.exports.router = router;
74module.exports.reply = reply;
75module.exports.utils = {
76 modern: modern
77};
78module.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];