This repository has been archived by the owner on Dec 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (70 loc) · 2.19 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
const fs = require('fs')
const path = require('path')
const yaml = require('js-yaml')
const _ = require('lodash')
const scaffold = require('./scaffold')
const mapFilename = '.map.json'
const defaultOptions = {
scaffold: true,
controllersDirectory: './controllers'
}
module.exports = {
/*
* add routes to passed router from swagger spec passed via filepath
*/
get(router, filepath, ops = {}) {
const options = Object.assign(defaultOptions, ops)
function getPath(path) {
return options.controllersDirectory + '/' + path
}
// load yaml to spec object
try {
var spec = yaml.safeLoad(fs.readFileSync(filepath, 'utf8'))
} catch (e) {
return Error(e)
}
// get endpoint objects from spec
const endpoints = Object.keys(spec.paths).map(endpoint => ({
path: endpoint,
methods: spec.paths[endpoint]
}))
if(options.scaffold) {
scaffold.init(endpoints, options)
}
// create routes from endpoint objects
for(let key in endpoints) {
let endpoint = endpoints[key]
endpointPath = endpoint.path.replace(/{(.*?)}/, match => ':'+match.substr(1, match.length - 2) )
let route = router.route(endpointPath)
for(var method in endpoint.methods) {
let name = endpoint.methods[method].operationId
if(name === undefined) {
return Error('controller not defined for ' + endpoint.path)
}
// detect method i.e operationId change of name under same path
if(options.scaffold) {
scaffold.rename(endpoint, method)
}
let controllerPath = path.resolve(getPath(name))
if(!fs.existsSync(controllerPath+'.js')) {
if(options.scaffold) {
scaffold.new(name, controllerPath)
} else {
console.warn(`Controller file not found for ${name}.`)
continue
}
}
// require controller module and link to route
let handler
try {
handler = require(controllerPath)
}
catch(e) {
return Error(`<${name}> controller module failed to load: ${e}`)
}
route = route[method](handler)
}
}
return router
}
}