-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
194 lines (166 loc) · 6.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
'use strict'
const httpErrors = require('http-errors')
const Router = require('router')
const SwaggerParser = require('swagger-parser')
const ui = require('./lib/ui')
const makeValidator = require('./lib/validate')
const { get: getSchema, set: setSchema } = require('./lib/layer-schema')
const minimumViableDocument = require('./lib/minimum-doc')
const generateDocument = require('./lib/generate-doc')
const defaultRoutePrefix = '/openapi'
const YAML = require('yaml')
module.exports = function ExpressOpenApi (_routePrefix, _doc, _opts) {
// Acceptable arguments:
// oapi()
// oapi('/path')
// oapi('/path', doc)
// oapi('/path', doc, opts)
// oapi(doc)
// oapi(doc, opts)
//
// The below logic is correct, but very hard to reason about
let routePrefix = _routePrefix || defaultRoutePrefix
let doc = _doc || minimumViableDocument
let opts = _opts || {}
if (typeof _routePrefix !== 'string') {
routePrefix = defaultRoutePrefix
doc = _routePrefix || minimumViableDocument
opts = _doc || {}
}
// We need to route a bit, seems a safe addition
// to use the express router in an express middleware
const router = new Router()
// Fully generate the doc on the first request
let isFirstRequest = true
// Where the magic happens
const middleware = function OpenApiMiddleware (req, res, next) {
if (isFirstRequest) {
middleware.document = generateDocument(middleware.document, req.app._router || req.app.router, opts.basePath)
isFirstRequest = false
}
router.handle(req, res, next)
}
// Expose the current document and prefix
middleware.routePrefix = routePrefix
middleware.document = generateDocument(doc, undefined, opts.basePath)
middleware.generateDocument = generateDocument
middleware.options = opts
// Add a path schema to the document
middleware.path = function (schema = {}) {
function schemaMiddleware (req, res, next) {
next()
}
setSchema(schemaMiddleware, schema)
return schemaMiddleware
}
// Validate path middleware
middleware.validPath = function (schema = {}, pathOpts = {}) {
let validate
function validSchemaMiddleware (req, res, next) {
if (!validate) {
validate = makeValidator(middleware, getSchema(validSchemaMiddleware), { ...pathOpts, ...opts })
}
return validate(req, res, next)
}
setSchema(validSchemaMiddleware, schema)
return validSchemaMiddleware
}
// Component definitions
middleware.component = function (type, name, description) {
if (!type) {
throw new TypeError('Component type is required')
}
// Return whole component type
if (!name && !description) {
return middleware.document.components && middleware.document.components[type]
}
// Return ref to type
if (name && !description) {
if (!middleware.document.components || !middleware.document.components[type] || !middleware.document.components[type][name]) {
throw new Error(`Unknown ${type} ref: ${name}`)
}
return { $ref: `#/components/${type}/${name}` }
}
// @TODO create id
// Is this necessary? The point of this was to provide canonical component ref urls
// But now I think that might not be necessary.
// if (!description || !description['$id']) {
// const server = middleware.document.servers && middleware.document.servers[0] && middleware.document.servers[0].url
// console.log(`${server || '/'}{routePrefix}/components/${type}/${name}.json`)
// description['$id'] = `${middleware.document.servers[0].url}/${routePrefix}/components/${type}/${name}.json`
// }
// Set name on parameter if not passed
if (type === 'parameters') {
description.name = description.name || name
}
// Define a new component
middleware.document.components = middleware.document.components || {}
middleware.document.components[type] = middleware.document.components[type] || {}
middleware.document.components[type][name] = description
return middleware
}
middleware.schema = middleware.component.bind(null, 'schemas')
middleware.response = middleware.component.bind(null, 'responses')
middleware.parameters = middleware.component.bind(null, 'parameters')
middleware.examples = middleware.component.bind(null, 'examples')
middleware.requestBodies = middleware.component.bind(null, 'requestBodies')
middleware.headers = middleware.component.bind(null, 'headers')
middleware.securitySchemes = middleware.component.bind(null, 'securitySchemes')
middleware.links = middleware.component.bind(null, 'links')
middleware.callbacks = middleware.component.bind(null, 'callbacks')
// Expose ui middleware
middleware.swaggerui = (options) => ui.serveSwaggerUI(`${routePrefix}.json`, options)
// OpenAPI document as json
router.get(`${routePrefix}.json`, (req, res) => {
middleware.document = generateDocument(middleware.document, req.app._router || req.app.router, opts.basePath)
res.json(middleware.document)
})
// OpenAPI document as yaml
router.get([`${routePrefix}.yaml`, `${routePrefix}.yml`], (req, res) => {
const jsonSpec = generateDocument(middleware.document, req.app._router || req.app.router, opts.basePath)
const yamlSpec = YAML.stringify(jsonSpec)
res.type('yaml')
res.send(yamlSpec)
})
router.get(`${routePrefix}/components/:type/:name.json`, (req, res, next) => {
const { type, name } = req.params
middleware.document = generateDocument(middleware.document, req.app._router || req.app.router, opts.basePath)
// No component by that identifer
if (!middleware.document.components[type] || !middleware.document.components[type][name]) {
return next(httpErrors(404, `Component does not exist: ${type}/${name}`))
}
// Return component
res.json(middleware.document.components[type][name])
})
// Validate full open api document
router.get(`${routePrefix}/validate`, (req, res) => {
middleware.document = generateDocument(middleware.document, req.app._router || req.app.router, opts.basePath)
SwaggerParser.validate(middleware.document, (err, api) => {
if (err) {
return res.json({
valid: false,
details: err.details,
document: middleware.document
})
}
res.json({
valid: true,
document: middleware.document
})
})
})
// Serve up the for exploring the document
if (opts.htmlui) {
let ui = opts.htmlui
if (!Array.isArray(opts.htmlui)) {
ui = [opts.htmlui]
}
if (ui.includes('swagger-ui')) {
router.get(`${routePrefix}`, (req, res) => { res.redirect(`${routePrefix}/swagger-ui`) })
router.use(`${routePrefix}/swagger-ui`, middleware.swaggerui)
}
}
return middleware
}
module.exports.minimumViableDocument = minimumViableDocument
module.exports.defaultRoutePrefix = defaultRoutePrefix