All files / src/join index.js

63.64% Statements 14/22
25% Branches 2/8
100% Functions 3/3
61.9% Lines 13/21
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 481x 1x 1x     1x 6x                       1x     1x     1x 1x 6x   6x                   6x 6x                
const load = require('loadware');
const assert = require('assert');
const reply = require('../../reply');
 
// Recursively resolve possible function returns and assign the value to .ret
const processReturn = async (ctx, ret) => {
  Eif (!ret) return;
 
  // Use the returned reply instance
  if (ret.constructor.name === 'Reply') {
    return await ret.exec(ctx);
  }
 
  // Create a whole new reply thing
  return await reply.send(ret).exec(ctx);
};
 
// Pass an array of modern middleware and return a single modern middleware
module.exports = (...middles) => {
 
  // Flattify all of the middleware
  const middle = load(middles);
 
  // Go through each of them
  return async ctx => {
    for (const mid of middle) {
      try {
        // DO NOT MERGE; the else is relevant only for ctx.error
        Iif (ctx.error) {
          // See if this middleware can fix it
          if (mid.error) {
            assert(mid.error instanceof Function, 'Error handler should be a function');
            let ret = await mid.error(ctx);
            await processReturn(ctx, ret);
          }
        }
        // No error, call next middleware. Skips middleware if there's an error
        else {
          let ret = await mid(ctx);
          await processReturn(ctx, ret);
        }
      } catch (err) {
        ctx.error = err;
      }
    }
  };
};