This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
osprey-mock-service.js
233 lines (211 loc) · 6.02 KB
/
osprey-mock-service.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
const Negotiator = require('negotiator')
const ospreyResources = require('osprey-resources')
const osprey = require('osprey')
const ramlSanitize = require('raml-sanitize')()
/**
* Export the mock server.
*/
module.exports = ospreyMockServer
module.exports.createServer = createServer
module.exports.createServerFromBaseUri = createServerFromBaseUri
module.exports.loadFile = loadFile
/**
* Create an Osprey server instance.
*
* @param {webapi-parser.WebApiDocument} model
* @return {Function}
*/
function ospreyMockServer (model) {
return ospreyResources(model.encodes.endPoints, mockHandler)
}
/**
* Create a server with Osprey and the mock service.
*
* @param {webapi-parser.WebApiDocument} model
* @param {Object} options
* @return {Function}
*/
function createServer (model, options) {
const app = osprey.Router()
app.use(osprey.server(model, options))
app.use(ospreyMockServer(model))
app.use(osprey.errorHandler())
return app
}
/**
* Create a mock service using the base uri path.
*
* @param {webapi-parser.WebApiDocument} model
* @param {Object} options
* @return {Function}
*/
function createServerFromBaseUri (model, options) {
const app = osprey.Router()
const serverEl = model.encodes.servers[0]
const baseUri = (serverEl && serverEl.url.option) || ''
const path = baseUri.replace(/^(\w+:)?\/\/[^/]+/, '') || '/'
const baseUriParameters = (serverEl && serverEl.variables) || []
app.use(path, baseUriParameters, createServer(model, options))
return app
}
/**
* Create a mock service from a filename.
*
* @param {String} fpath
* @param {Object} options
* @return {Function}
*/
async function loadFile (fpath, options) {
const wap = require('webapi-parser').WebApiParser
fpath = fpath.startsWith('file:') ? fpath : `file://${fpath}`
let model, resolved
try {
model = await wap.raml10.parse(fpath)
resolved = await wap.raml10.resolve(model)
} catch (e) {
model = await wap.raml08.parse(fpath)
resolved = await wap.raml08.resolve(model)
}
return createServerFromBaseUri(resolved, options || {})
}
/**
* Returns a single example of the body.
*
* @param {webapi-parser.AnyShape} schema
*/
function getSchemaExample (schema) {
const exNode = schema.examples && schema.examples[0]
if (!exNode) {
return
}
const exValue = exNode.value.option && exNode.value.option.trim()
const isJson = exValue && exValue.startsWith('{')
const isXml = exValue && exValue.startsWith('<')
const isStructured = !!exNode.structuredValue
if (!isStructured || isJson || isXml) {
return exValue
}
return extractDataNodeValue(exNode.structuredValue)
}
/**
* Extracts data from DataNode subclass instance.
*
* @param {webapi-parser.DataNode} dNode
*/
function extractDataNodeValue (dNode) {
// ScalarNode
if (dNode.dataType !== undefined) {
return dNode.value.option
}
// ArrayNode
if (dNode.members !== undefined) {
return dNode.members.map(extractDataNodeValue)
}
// ObjectNode
if (dNode.properties !== undefined) {
const data = {}
Object.keys(dNode.properties).forEach(name => {
data[name] = extractDataNodeValue(dNode.properties[name])
})
if (Object.keys(data).length > 0) {
return data
}
}
}
/**
* Returns a single example of the header.
*
* @param {webapi-parser.Parameter} header
*/
function getHeaderExample (header) {
const example = (
header.schema.examples &&
header.schema.examples[0] &&
header.schema.examples[0].value.option)
return example ? example.trim() : undefined
}
/**
* Create a RAML example method handler.
*
* @param {webapi-parser.Operation} method
* @return {Function}
*/
function mockHandler (method) {
const response = method.responses && method.responses[0]
const statusCode = response
? parseInt(response.statusCode.value())
: 200
// Set up the default response headers.
const headers = {}
if (response && response.headers) {
response.headers.forEach(header => {
const defaultVal = (
header.schema.defaultValueStr &&
header.schema.defaultValueStr.option)
const example = getHeaderExample(header)
if (defaultVal) {
headers[header.name.value()] = defaultVal
} else if (example) {
headers[header.name.value()] = example
}
})
}
const bodies = {}
if (response) {
response.payloads.forEach(pl => {
bodies[pl.mediaType.value()] = pl
})
}
const types = Object.keys(bodies)
return function (req, res) {
const negotiator = new Negotiator(req)
let type = negotiator.mediaType(types)
if (req.params && (req.params.mediaTypeExtension || req.params.ext)) {
let ext = req.params.mediaTypeExtension || req.params.ext
ext = ext.slice(1)
type = 'application/' + ext
}
const body = bodies[type] || {}
res.statusCode = statusCode
setHeaders(res, headers)
if (type) {
res.setHeader('Content-Type', type)
const example = getSchemaExample(body.schema)
const sanitizer = ramlSanitize(body.schema.properties)
const sanitize = (obj) => typeof obj === 'object' ? sanitizer(obj) : obj
if (example) {
res.write(typeof example !== 'string'
? JSON.stringify(sanitize(example))
: example)
} else {
let propertiesExample
if (body && body.schema && body.schema.properties) {
propertiesExample = {}
body.schema.properties.forEach(prop => {
const exampleVal = getSchemaExample(prop.range)
if (exampleVal) {
propertiesExample[prop.name.value()] = exampleVal
}
})
}
if (propertiesExample) {
res.write(typeof propertiesExample === 'object'
? JSON.stringify(sanitize(propertiesExample))
: propertiesExample)
}
}
}
res.end()
}
}
/**
* Set a map of headers on the response.
*
* @param {HTTP.Response} res
* @param {Object} headers
*/
function setHeaders (res, headers) {
Object.keys(headers).forEach(function (key) {
res.setHeader(key, headers[key])
})
}