-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
connector.js
51 lines (44 loc) · 1.77 KB
/
connector.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
const extractVersion = require('./extract/extractVersion')
const ERRORS = require('./errors')
const extractV2Paths = require('./extract/v2/extractPaths')
const extractV3Paths = require('./extract/v3/extractPaths')
const connectSecurity = require('./connectors/connectSecurity')
const connectController = require('./connectors/connectController')
/**
* Connect the route controllers defined in `api` with the
* `operationIds` and `paths` in the `apiDoc` supplied.
* The `apiDoc` may be either a Swagger version 2,
* or OpenAPI version 3 document.
* The options allowed, with their defaults are as follows:
* {
* apiSeparator = '_'
* notFound = src/routes/notFound
* notImplemented = src/routes/notImplemented
* onCreateRoute
* rootTag = 'root' // ignored if using OpenAPI v3
* security = {}
* variables = {},
* middleware = {},
* INVALID_VERSION = errors.INVALID_VERSION
* }
*/
const connector = (api, apiDoc, options = {}) => {
const { INVALID_VERSION = ERRORS.INVALID_VERSION, onCreateRoute } = options
const version = extractVersion(apiDoc)
if (!version) throw new Error(INVALID_VERSION)
const extractPaths = version === 2 ? extractV2Paths : extractV3Paths
const paths = extractPaths(apiDoc, options)
return app => {
paths.forEach(({ method, route, operationId, security, middleware }) => {
const auth = connectSecurity(security, options)
const controller = connectController(api, operationId, options)
const descriptor = [route]
if (auth) descriptor.push(auth)
if (middleware.length) descriptor.push(...middleware)
descriptor.push(controller)
app[method](...descriptor)
if (typeof onCreateRoute === 'function') onCreateRoute(method, descriptor)
})
}
}
module.exports = connector