-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (51 loc) · 1.65 KB
/
index.js
File metadata and controls
62 lines (51 loc) · 1.65 KB
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
const parser = require('ruo-swagger-parser')
const parseUrl = require('url').parse
const fs = require('fs')
const _ = require('lodash')
const Path = require('./path')
const rc = require('../rc')
class Swagger {
static async createAsync (dynamicDefinition) {
const root = rc.target
const cachePath = root + '/spec/swagger.json'
if (rc.useSwaggerCache && fs.existsSync(cachePath)) {
const cached = JSON.parse(fs.readFileSync(cachePath, 'utf8'))
return new Swagger(_.merge(cached, dynamicDefinition))
}
const definition = await parser(root,
'**/*' + rc.suffix.spec,
rc.suffix.spec,
'api',
rc.shadow
)
return new Swagger(_.merge(definition, dynamicDefinition))
}
constructor (definition) {
this.definition = definition
_.assign(this, definition)
let basePathPrefix = definition.basePath || '/'
// Remove trailing slash from the basePathPrefix so we do not end up with double slashes
if (basePathPrefix.charAt(basePathPrefix.length - 1) === '/') {
basePathPrefix = basePathPrefix.substring(0, basePathPrefix.length - 1)
}
this.basePathPrefix = basePathPrefix
this.pathObjects = _.map(definition.paths, (pathDef, path) => {
return new Path(path, pathDef, this, ['paths', path])
})
}
getPath (url) {
return _.find(this.pathObjects, (pathObject) => {
return _.isArray(pathObject.regexp.exec(url))
})
}
getOperation (req) {
const url = parseUrl(req.url).pathname
const method = req.method
const path = this.getPath(url)
if (!path) {
return undefined
}
return path.getOperation(method)
}
}
exports.Swagger = Swagger