git ssb

1+

dinoworm ๐Ÿ› / http-routes



Tree: fa11a79692a0715b585e25e0ddbeef8c39e0d6fa

Files: fa11a79692a0715b585e25e0ddbeef8c39e0d6fa / index.js

1683 bytesRaw
1const assign = Object.assign
2const compose = require('http-compose')
3const pathToRegexp = require('path-to-regexp')
4const zipObject = require('@f/zip-obj')
5
6module.exports = Routes
7
8function Routes (routes) {
9 if (typeof arguments[0] === 'string') {
10 return Routes([[arguments[0], arguments[1]]])
11 } else if (arguments[0].length === 2 && typeof arguments[0][0] === 'string') {
12 return Routes([arguments[0]])
13 }
14
15 return compose(routes.map(route => {
16 if (typeof route === 'function') return route
17 const path = route[0]
18 const handler = route[1]
19 return mount(path, byMethod(handler))
20 }))
21}
22
23function byMethod (handler) {
24 const methodNames = Object.keys(handler)
25 return typeof handler === 'function'
26 ? ifMethod(handler, 'get')
27 : compose(methodNames.map(methodName => {
28 return ifMethod(handler[methodName], methodName)
29 }))
30}
31
32function ifMethod (handler, methodName) {
33 var METHOD = methodName.toUpperCase()
34 return function (req, res, context, next) {
35 if (req.method !== METHOD) next()
36 else handler(req, res, context, next)
37 }
38}
39
40function mount (path, handler) {
41 var keys = []
42 const query = pathToRegexp(path, keys)
43 return function (req, res, context, next) {
44 const url = context && context.url || req.url
45 const matches = query.exec(url)
46 if (matches === null) return next()
47
48 const nextUrl = req.url.substring(matches[0].length)
49
50 const keyNames = keys.map(key => key.name)
51 const params = zipObject(keyNames, matches.slice(1))
52 const nextContext = assign({}, context, {
53 url: nextUrl,
54 params: assign(context.params || {}, params)
55 })
56
57 handler(req, res, nextContext, next)
58 }
59}
60

Built with git-ssb-web