All files / server server.js

100% Statements 32/32
100% Branches 0/0
100% Functions 6/6
100% Lines 28/28
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      27x 27x 27x 27x     27x       6753x       27x     117x               117x     117x     1160x     116x 464x         116x     116x 232x       116x 116x     116x 115x 115x       116x         27x 27x 27x 27x 27x   27x  
// server for Node.js (https://serverjs.io/)
// A simple and powerful server for Node.js.
 
const router = require('./router');
const reply = require('./reply');
const utils = require('./utils');
const plugins = require('./plugins');
 
// Parse the configuration
const config = require('./src/config');
 
// Get the functions from the plugins for a special point
// This implies a hook can only be a function, not an array of fn
const hook = (ctx, name) => ctx.plugins.map(p => p[name]).filter(p => p);
 
 
// Main function
const Server = async (...all) => {
 
  // Initialize the global context from the Server properties
  const ctx = {
    router,
    reply,
    utils,
    plugins,
  };
 
  // Extract the options and middleware
  const { opts, middle } = ctx.utils.normalize(all);
 
  // Set the options for the context of Server.js
  ctx.options = await config(opts, Server.plugins);
 
  // Only allow plugins that were manually enabled through the options
  ctx.plugins = ctx.plugins.filter(p => ctx.options[p.name]);
 
  // All the init beforehand
  for (let init of hook(ctx, 'init')) {
    await init(ctx);
  }
 
  // Set the whole middleware thing into 'middle'
  // It has to be here since `init` might modify some of these
  ctx.middle = ctx.utils.join(hook(ctx, 'before'), middle, hook(ctx, 'after'));
 
  // Different listening methods in series
  for (let listen of hook(ctx, 'listen')) {
    await listen(ctx);
  }
 
  // Different listening methods in series
  for (let launch of hook(ctx, 'launch')) {
    await launch(ctx);
  }
 
  ctx.close = async () => {
    for (let close of hook(ctx, 'close')) {
      await close(ctx);
    }
  };
 
  return ctx;
};
 
// Internal modules. It has to be after the exports for `session`
// to be defined, since it is defined in a plugin
Server.router = router;
Server.reply = reply;
Server.utils = utils;
Server.plugins = plugins;
Server.session = require('express-session');
 
module.exports = Server;