All files / server/router generic.js

100% Statements 16/16
100% Branches 6/6
100% Functions 2/2
100% Lines 13/13
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 3132x 32x     32x     39x   39x   39x     48x     40x     36x 36x 30x     30x   30x      
const normalize = require('../utils/normalize');
const params = require('path-to-regexp-wrap')();
 
// Generic request handler
module.exports = (method, ...all) => {
 
  // Extracted or otherwise it'd shift once per call; also more performant
  const { path, middle } = normalize(all);
 
  const match = params(path);
 
  return async ctx => {
 
    // A route should be replied only once per request
    if (ctx.replied) return;
 
    // Only for the correct method
    if (method !== ctx.method) return;
 
    // Only do this if the correct path
    ctx.params = match(ctx.path);
    if (!ctx.params) return;
    ctx.params = ctx.params;
 
    // Perform this promise chain
    await ctx.utils.join(middle)(ctx);
 
    ctx.replied = true;
  };
};