-
-
Notifications
You must be signed in to change notification settings - Fork 210
/
index.js
85 lines (65 loc) · 2.78 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
'use strict'
const yaml = require('yaml')
const { shouldRouteHide } = require('../../util/should-route-hide')
const { prepareDefaultOptions, prepareOpenapiObject, prepareOpenapiMethod, prepareOpenapiSchemas, normalizeUrl, resolveServerUrls } = require('./utils')
module.exports = function (opts, cache, routes, Ref, done) {
let ref
const defOpts = prepareDefaultOptions(opts)
return function (opts) {
if (opts && opts.yaml) {
if (cache.string) return cache.string
} else {
if (cache.object) return cache.object
}
// Base Openapi info
const openapiObject = prepareOpenapiObject(defOpts, done)
ref = Ref()
openapiObject.components.schemas = prepareOpenapiSchemas({
...openapiObject.components.schemas,
...(ref.definitions().definitions)
}, ref)
const serverUrls = resolveServerUrls(defOpts.servers)
for (const route of routes) {
const transformResult = route.config?.swaggerTransform !== undefined
? route.config.swaggerTransform
? route.config.swaggerTransform({ schema: route.schema, url: route.url, route, openapiObject })
: {}
: defOpts.transform
? defOpts.transform({ schema: route.schema, url: route.url, route, openapiObject })
: {}
const schema = transformResult.schema || route.schema
const shouldRouteHideOpts = {
hiddenTag: defOpts.hiddenTag,
hideUntagged: defOpts.hideUntagged
}
if (shouldRouteHide(schema, shouldRouteHideOpts)) continue
let url = transformResult.url || route.url
url = normalizeUrl(url, serverUrls, defOpts.stripBasePath)
const openapiRoute = Object.assign({}, openapiObject.paths[url])
const openapiMethod = prepareOpenapiMethod(schema, ref, openapiObject, url)
if (route.links) {
for (const statusCode of Object.keys(route.links)) {
if (!openapiMethod.responses[statusCode]) {
throw new Error(`missing status code ${statusCode} in route ${route.path}`)
}
openapiMethod.responses[statusCode].links = route.links[statusCode]
}
}
// route.method should be either a String, like 'POST', or an Array of Strings, like ['POST','PUT','PATCH']
const methods = typeof route.method === 'string' ? [route.method] : route.method
for (const method of methods) {
openapiRoute[method.toLowerCase()] = openapiMethod
}
openapiObject.paths[url] = openapiRoute
}
const transformObjectResult = defOpts.transformObject
? defOpts.transformObject({ openapiObject })
: openapiObject
if (opts && opts.yaml) {
cache.string = yaml.stringify(transformObjectResult, { strict: false })
return cache.string
}
cache.object = transformObjectResult
return cache.object
}
}