-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
51 lines (47 loc) · 1.65 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
const raml2obj = require('raml2obj');
const express = require('express')
const app = express()
const paramUrlRegex = /\{([^\{]*)\}/g
// TODO param enum
function addMockApi(r){
let apiPath = r.parentUrl + r.relativeUri
apiPath = apiPath.replace(paramUrlRegex, ':$1')
r.methods && r.methods.forEach((m) => {
const responseMap = {}
console.log(m.method, apiPath)
m.responses && m.responses.forEach(response => {
if(response.body && response.body[0].examples){
responseMap[response.code] = response.body[0].examples[0].value
}else {
// TODO fake data
responseMap[response.code] = {}
}
})
app[m.method](apiPath, (req, res) => {
const code = req.query['__code']
m.allUriParameters && m.allUriParameters.forEach(uriParam => {
if(uriParam.required && req.params[uriParam.key] === undefined){
res.status(400).send(`url param [${uriParam.key}] is required`)
}
})
m.queryParameters && m.queryParameters.forEach(queryParam => {
if(queryParam.required && req.query[queryParam.key] === undefined){
res.status(400).send(`query param [${queryParam.key}] is required`)
}
})
// m.body.forEach(field => {
// })
if (code && responseMap[code]) {
res.send(responseMap[code])
} else {
res.send(responseMap[200] || Object.values(responseMap)[0])
}
})
})
r.resources && r.resources.forEach(addMockApi)
}
raml2obj.parse('examples/marathon/api.raml').then((ramlObj) => {
ramlObj.resources && ramlObj.resources.forEach(addMockApi)
app.listen(3000)
console.log('pampas api mocker started, listen on 3000')
})