-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
109 lines (82 loc) · 2.25 KB
/
index.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
let expressRoutes = {}
const flatten = require('flat') // Pending formal consent: https://github.com/hughsk/flat/issues/73
module.exports = function(routes, config) {
let skipParse = false
if (config && config.skipParse)
skipParse = true
if (!skipParse)
routes = require('expressive-parser')(routes)
expressRoutes.GET = {}
expressRoutes.PUT = {}
expressRoutes.POST = {}
expressRoutes.DELETE = {}
expressRoutes.IGNORE = {}
for (let route of routes) {
const method = methodForRoute(route)
const path = `/${route.path.replace(/\./g, '/')}` // Replace all route periods with forward slashes
if (!expressRoutes[method])
expressRoutes[method] = {}
expressRoutes[method][path] = route.fn
}
return function(req, res, next) {
if (!expressRoutes[req.method])
return res.status(500).end('Unknown HTTP method')
let route = expressRoutes[req.method][req.path]
if (!route)
if (config.routeNotFound)
return res.status(404).end(config.routeNotFound)
else
return next()
const callback = routeCallback(res, config)
const context = {
protocol: 'express',
server: true,
method: req.method,
callback: callback,
req: res,
res: res,
next: next,
}
let params = {}
if (req.method == 'GET')
params = flatten.unflatten(req.query, { safe: true, object: true })
else
params = req.body
route(context, params, callback)
}
}
function methodForRoute(route) {
switch (route.type) {
case 'create':
return 'POST'
case 'read':
return 'GET'
case 'update':
return 'PUT'
case 'delete':
return 'DELETE'
case 'list':
return 'GET'
default:
return 'GET'
}
}
function routeCallback(res, config) {
return function responseCallback(err, data) {
let status = 200
if (err) {
if (typeof err === 'object' && err.status)
status = err.status
else
status = 404
if (!config.statusInResponse)
delete err.status
return res.status(status).send(err)
}
if (typeof data === 'object' && data.status)
status = data.status
if (!config.statusInResponse)
delete data.status
res.status(status).send(data)
}
}