All files / server/router generic.js

95% Statements 19/20
75% Branches 6/8
100% Functions 3/3
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3727x 27x 27x   27x     27x   39x     39x   39x   39x     39x     35x 35x 30x     30x   3x 3x 3x          
const join = require('../src/join');
const parse = require('./parse');
const { match } = require('path-to-regexp');
 
const decode = decodeURIComponent;
 
// Generic request handler
module.exports = (method, ...all) => {
  // Extracted or otherwise it'd shift once per call; also more performant
  const { path, middle } = parse(all);
 
  // Convert to the proper path, since the new ones use `(.*)` instead of `*`
  const parsePath = match(path.replace(/\*/g, '(.*)'), { decode: decode });
 
  return async ctx => {
    // A route should be solved only once per request
    Iif (ctx.req.solved) return;
 
    // Only for the correct method
    if (method !== ctx.req.method) return;
 
    // Only do this if the correct path
    ctx.req.params = parsePath(ctx.req.path).params;
    if (!ctx.req.params) return;
    ctx.params = ctx.req.params;
 
    // Perform this promise chain
    await join(middle, ctx => {
      // Only solve it if all the previous middleware succeeded
      ctx.req.solved = true;
      Eif (!ctx.res.headersSent) {
        ctx.res.end();
      }
    })(ctx);
  };
};