All files / server/utils/modern index.js

91.67% Statements 11/12
75% Branches 3/4
100% Functions 4/4
90% Lines 9/10
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      12x         12x     12x     1205x     1198x     1193x       1189x     1189x     1189x      
// Modern - Create a modern middleware from the old-style one
 
// Valid HTTP methods acording to RFC 7231 and RFC 5789
const methods = [
  'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE'
];
 
// Cleanly validate data
const validate = require('./validate');
 
// Pass it an old middleware and return a new one 'ctx => promise'
module.exports = middle => {
 
  // Validate it early so no requests need to be made
  validate.middleware(middle);
 
  // Create and return the modern middleware function
  return ctx => new Promise((resolve, reject) => {
 
    // modern() only works for HTTP requests
    Iif (!methods.includes(ctx.method.toUpperCase())) {
      return resolve();
    }
 
    validate.context(ctx);
 
    // It can handle both success or errors. Pass the right ctx
    const next = err => err ? reject(err) : resolve();
 
    // Call the old middleware
    middle(ctx.req, ctx.res, next);
  });
};