-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmock.config.js
74 lines (68 loc) · 1.68 KB
/
mock.config.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
function createRandomString() {
return Math.random()
.toString(16)
.slice(2)
}
function Response(code, data) {
this.statusCode = code
this.data = data
}
const apis = {
/**
* 'METHOD ROUTE': function requestHandler(request, response) {}
*/
'GET /user/abilities': function(req, res) {
res.json(
new Response(
200,
[
'github.user.read',
'github.user.write',
'github.sample.read',
'github.sample.write',
'npm.org.read',
'npm.org.write',
'npm.package.read',
'npm.package.write',
'github.repo.read',
'github.repo.write',
'github.action.read',
'github.action.write'
].map(name => ({
name,
uid: createRandomString(),
createAt: Date.now()
}))
)
)
},
'POST /user/profile': function(req, res) {
res.json(
new Response(200, {
token: createRandomString()
})
)
}
}
module.exports = function mocker(app) {
const methodsReg = /^(?:GET|POST|DELETE|PUT|PATCH|OPTION)$/i
const routeReg = /^\/.+/
Object.keys(apis).forEach(api => {
const [method, route] = api.split(' ')
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*'
}
app.use(function(request, response, next) {
Reflect.ownKeys(corsHeaders).forEach(header =>
response.setHeader(header, corsHeaders[header])
)
next()
})
if (methodsReg.test(method) && routeReg.test(route)) {
app[method.toLowerCase()](route, apis[api])
} else {
console.error('[MOCK]: Unexpected method or route')
}
})
}