All files / take-five take-five.js

100% Statements 44/44
91.67% Branches 11/12
100% Functions 10/10
100% Lines 42/42
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 651x 1x 1x   1x   1x 1x 1x 1x 1x 1x   1x 5x 5x 5x 5x 5x 5x 20x     5x 16x 16x   16x     5x 1x 1x 4x 1x 1x     1x     5x 5x 5x 20x   5x     14x 8x     14x 13x     14x 12x 12x 12x        
const path = require('path')
const http = require('http')
const querystring = require('querystring')
 
const wayfarer = require('wayfarer')
 
const handleRequest = require('./lib/handle-request')
const cors = require('./lib/cors')
const parseBody = require('./lib/parse-body')
const restrictPost = require('./lib/restrict-post')
const makeRes = require('./lib/make-res')
const methods = ['get', 'put', 'post', 'delete']
 
module.exports = function (opts) {
  opts = opts || {}
  opts.maxPost = opts.maxPost || 512 * 1024
  const routers = new Map()
  const middleware = []
  const server = http.createServer()
  methods.forEach(m => {
    server[m] = (matcher, func) => addRoute(m, matcher, func)
  })
 
  server.use = (funcs) => {
    Eif (!Array.isArray(funcs)) {
      funcs = [funcs]
    }
    middleware.push.apply(middleware, funcs)
  }
 
  server.router = (ns) => {
    const router = {}
    methods.forEach(m => {
      router[m] = (matcher, func) => {
        const nsMatcher = path.join(ns, matcher)
        addRoute(m, nsMatcher, func)
      }
    })
    return router
  }
 
  server.use(cors(opts.cors || {}))
  server.use(restrictPost(opts.maxPost))
  server.use(parseBody(opts.maxPost))
  server.on('request', (req, res) => handleRequest(req, makeRes(res), middleware, routers))
 
  return server
 
  function addRoute (method, matcher, funcs) {
    if (!routers.has(method)) {
      routers.set(method, wayfarer('/_'))
    }
 
    if (!Array.isArray(funcs)) {
      funcs = [funcs]
    }
 
    routers.get(method).on(matcher, (params, req, res) => {
      req.params = querystring.parse(req.url.split('?')[1])
      req.urlParams = params
      handleRequest(req, res, funcs)
    })
  }
}