All files / server/plugins/core init.js

83.78% Statements 31/37
65% Branches 13/20
60% Functions 3/5
83.78% Lines 31/37
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 8114x   60x 60x     60x 60x     60x 60x 60x               60x 60x 60x 60x       60x     60x 60x 60x           60x 41x 41x     41x 35x 35x                   60x 1x 1x       60x                   60x 54x 5179x 5125x     54x      
module.exports = async ctx => {
 
  const modern = ctx.utils.modern;
  const opts = ctx.options.core;
 
  // TODO: fix it so this is not needed
  const core = require('.');
  core.before = [];
 
  // Compress
  Eif (opts.compress) {
    const compress = require('compression')(opts.compress);
    core.before.push(modern(compress));
  }
 
  // Public folder
  // if (opts.public) {
  //   core.before.push(modern(ctx.express.static(opts.public)));
  // }
 
  Eif (opts.session) {
    opts.session.secret = opts.session.secret || ctx.options.secret;
    const session = require('express-session');
    Iif (ctx.options.redis_url) {
      let RedisStore = require('connect-redis')(session);
      opts.session.store = new RedisStore({ url: ctx.options.redis_url });
    }
    core.before.push(modern(session(opts.session)));
  }
 
  Eif (opts.timing) {
    const timing = require('response-time')(opts.timing);
    core.before.push(modern(timing));
  }
 
  // TODO: vhost: require('vhost')
  // - DO IT WITH A ROUTER
 
  if (opts.csrf) {
    const csrf = require('csurf')(opts.csrf);
    core.before.push(modern(csrf));
 
    // Set the csrf for render(): https://expressjs.com/en/api.html#res.locals
    core.before.push(ctx => {
      ctx.csrf = ctx.req.csrfToken();
      ctx.res.locals.csrf = ctx.csrf;
    });
  }
 
  // ctx => {
  //   if (!opts.middle) return;
  //   ?TODO: serveIndex: (opt, all) => require('serve-index')(all.public)
  // },
 
 
  if (opts.favicon) {
    const favicon = require('serve-favicon')(opts.favicon);
    core.before.push(modern(favicon));
  }
 
 
  Iif (opts.partials) {
    await new Promise((resolve, reject) => {
      const hbs = require('hbs');
      hbs.registerPartials(opts.partials, (err, done) => {
        return err ? reject(err) : resolve(done);
      });
    });
  }
 
  // Add a reference from ctx.req.body to the ctx.data and an alias
  core.before.push(ctx => {
    for (let key in ctx.req) {
      if (key !== 'host') {
        ctx[key] = ctx.req[key];
      }
    }
    ctx.data = ctx.body;
  });
};