-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.mjs
53 lines (50 loc) · 1.21 KB
/
json.mjs
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
import * as metro from '../metro.mjs'
export default function jsonmw(options) {
options = Object.assign({
mimetype: 'application/json',
reviver: null,
replacer: null,
space: ''
}, options)
return async (req, next) => {
if (!isJSON(req.headers.get('Accept'))) {
req = req.with({
headers: {
'Accept': options.mimetype
}
})
}
if (['POST','PUT','PATCH','QUERY'].includes(req.method)) {
if (req.data && typeof req.data=='object' && !(req.data instanceof ReadableStream)) {
if (!isJSON(req.headers.get('content-type'))) {
req = req.with({
headers: {
'Content-Type':options.mimetype,
}
})
}
req = req.with({
body: JSON.stringify(req.data, options.replacer, options.space)
})
}
}
let res = await next(req)
if (isJSON(res.headers.get('content-type'))) {
let tempRes = res.clone()
let body = await tempRes.text()
try {
let json = JSON.parse(body, options.reviver)
return res.with({
body: json
})
} catch(e) {
// ignore parse errors
}
}
return res
}
}
const jsonRE = /^application\/([a-zA-Z0-9\-_]+\+)?json\b/
function isJSON(contentType) {
return jsonRE.exec(contentType)
}