This repository has been archived by the owner on Oct 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
serve.js
59 lines (56 loc) · 1.7 KB
/
serve.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
'use strict'
const reserve = require('reserve/serve')
const log = require('reserve/log')
process.on('unhandledRejection', error => { // Absorb
console.log('unhandledRejection'.red, (error.message || error.toString()).gray)
})
module.exports = function ({
hostname = '127.0.0.1',
port = 8080,
mappings = [],
ssl,
verbose = process.argv.some(param => ['--verbose', '--debug'].includes(param)),
window
}) {
return log(reserve({
handlers: {
mock: {
schema: {},
redirect: ({ mapping, redirect, request, response }) => new Promise(resolve => {
const dataChunks = []
request
.on('data', chunk => dataChunks.push(chunk.toString()))
.on('end', () => {
let data
if (dataChunks.length) {
data = dataChunks.join('')
}
window.jQuery.ajax({
method: request.method,
url: redirect,
headers: request.headers,
data: data,
complete: jqXHR => {
jqXHR.getAllResponseHeaders()
.split('\n')
.filter(header => header)
.forEach(header => {
const pos = header.indexOf(':')
response.setHeader(header.substr(0, pos).trim(), header.substr(pos + 1).trim())
})
response.statusCode = jqXHR.status
const responseText = jqXHR.responseText
response.end(responseText)
resolve()
}
})
})
})
}
},
hostname,
port,
ssl,
mappings
}), verbose)
}