-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
68 lines (57 loc) · 2.21 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
let debug = process.env.NODE_ENV === 'development' ? true : false
module.exports = function (app, routes, options) {
if (!app) throw new Error('First argument of the router should be an express app')
routes = routes || []
options = options || {}
let defaults = {
controllerDirectory: process.cwd() + '/controllers/',
controllerFileSuffix: '-controller.js',
resourceRoutesTemplate: [
{ method: 'get', pathSuffix: '', action: 'index' },
{ method: 'get', pathSuffix: '/new', action: 'add' },
{ method: 'post', pathSuffix: '', action: 'create' },
{ method: 'get', pathSuffix: '/:id', action: 'show' },
{ method: 'get', pathSuffix: '/:id/edit', action: 'edit' },
{ method: 'put', pathSuffix: '/:id', action: 'update' },
{ method: 'delete', pathSuffix: '/:id', action: 'destroy' }
]
}
options = Object.assign({}, defaults, options)
routes = transformResourcesToRoutes(routes, options.resourceRoutesTemplate)
if (debug && (options.logRoutesList === false ? false : true)) console.log('app routes list:')
routes.forEach(route => generateRoute(app, route, options))
}
function transformResourcesToRoutes(routes, resourceRoutesTemplate) {
let output = []
routes.forEach((item, index) => {
if (!item.resource) {
output.push(item)
return
}
resourceRoutesTemplate.forEach((routeTemplate) => {
let route = {
method: routeTemplate.method,
path: item.resource + routeTemplate.pathSuffix,
controller: item.controller,
action: routeTemplate.action
}
output.push(route)
})
})
return output
}
function generateRoute(app, route, options) {
const middlewares = route.middlewares || []
const args = [route.path, ...middlewares, callback]
app[route.method].apply(app, args)
const controllerFilePath = options.controllerDirectory +
route.controller + options.controllerFileSuffix
const controller = require(controllerFilePath)
function callback(req, res, next) {
controller[route.action](req, res, next)
}
if (debug && (options.logRoutesList === false ? false : true)) {
console.log(`\t${route.method.toUpperCase()} ${route.path} ` +
`-> ${route.controller}.${route.action}`)
}
}