-
Notifications
You must be signed in to change notification settings - Fork 13
/
swagger.js
executable file
·150 lines (133 loc) · 4.36 KB
/
swagger.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
//import connect from 'connect';
import debug from 'debug'
import express from 'express'
import { readFileSync } from 'fs'
import { createServer } from 'http'
import { safeLoad } from 'js-yaml'
import pathUtil from 'path'
import { initializeMiddleware } from 'swagger-tools'
var app = express()
var serverPort = process.env.PORT || 8080
var logger = debug('api')
var error = debug('error')
error.log = console.error.bind(console) // eslint-disable-line no-console
// swaggerRouter configuration
var options = {
swaggerUi: pathUtil.join(__dirname, '/swagger.json'),
controllers: pathUtil.join(__dirname, './controllers'),
useStubs: process.env.NODE_ENV === 'development' // Conditionally turn on stubs (mock mode)
}
// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var spec = readFileSync(pathUtil.join(__dirname, 'api/swagger.yaml'), 'utf8')
export var swaggerDoc = safeLoad(spec)
global.swaggerDoc = swaggerDoc
export function swaggerInit() {
// Initialize the Swagger middleware
return new Promise(resolve => {
initializeMiddleware(swaggerDoc, function (middleware) {
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
const metaData = middleware.swaggerMetadata()
app.use(metaData)
// Validate Swagger requests
app.use(
middleware.swaggerValidator({
validateResponse:
process.env.NODE_ENV === undefined ||
process.env.NODE_ENV === 'development'
})
)
// Route validated requests to appropriate controller
app.use(middleware.swaggerRouter(options))
// Serve the Swagger documents and Swagger UI
app.use(
middleware.swaggerUi({
// apiDocs: '/api-docs',
// swaggerUi: '/docs',
})
)
app.use(function (error_, request, res, next) {
if (error_.failedValidation) {
// handle validation errror
const rehydratedError = Object.assign({}, error_)
if (error_.originalResponse) {
rehydratedError.originalResponse = JSON.parse(
error_.originalResponse
)
}
if (error_.message) {
rehydratedError.message = error_.message
}
if (error_.results) {
rehydratedError.errors = error_.results.errors
delete rehydratedError.results
}
error(
'error!!!',
error_.message,
JSON.stringify(rehydratedError, undefined, 2)
)
res
.status(error_.code === 'SCHEMA_VALIDATION_FAILED' ? '500' : '400')
.json(rehydratedError)
} else {
next()
}
})
global.swaggerApp = app
global.swaggerMiddleware = middleware
resolve({ app, middleware })
})
})
}
let server
export function startServer() {
app.use((request, response, next) => {
if (process.env.ADDRESSR_ACCESS_CONTROL_ALLOW_ORIGIN !== undefined) {
response.append(
'Access-Control-Allow-Origin',
process.env.ADDRESSR_ACCESS_CONTROL_ALLOW_ORIGIN
)
}
if (process.env.ADDRESSR_ACCESS_CONTROL_EXPOSE_HEADERS !== undefined) {
response.append(
'Access-Control-Expose-Headers',
process.env.ADDRESSR_ACCESS_CONTROL_EXPOSE_HEADERS
)
}
if (process.env.ADDRESSR_ACCESS_CONTROL_ALLOW_HEADERS !== undefined) {
response.append(
'Access-Control-Allow-Headers',
process.env.ADDRESSR_ACCESS_CONTROL_ALLOW_HEADERS
)
}
next()
})
return swaggerInit().then(({ app /*, middleware*/ }) => {
// logger(app);
// logger(middleware);
server = createServer(app)
server.listen(serverPort, function () {
logger(
'📡 Addressr is listening on port %d ( http://localhost:%d ) ',
serverPort,
serverPort
)
logger(
'📑 Swagger-ui is available on http://localhost:%d/docs',
serverPort
)
if (process.env.NODE_ENV !== 'PRODUCTION') {
// ngrok.connect(serverPort).then(url => {
// logger('📡 Addressr is listening at %s', url);
// logger('📑 Swagger-ui is available on %s/docs/', url);
// });
}
})
return `http://localhost:${serverPort}`
})
}
export function stopServer() {
if (server !== undefined) {
server.close()
}
}