-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (58 loc) · 1.41 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'use strict'
const getStream = require('get-stream')
const parsing = Symbol()
const parsed = Symbol()
class ContentTypeError extends Error {
constructor() {
super('Content-Type must be "application/json"')
this.name = this.constructor.name
}
}
class ParsingError extends Error {
constructor() {
super('Unable to parse JSON')
this.name = this.constructor.name
}
}
class BufferError extends Error {
constructor() {
super('Buffer exhausted')
this.name = this.constructor.name
}
}
parse.ContentTypeError = ContentTypeError
parse.ParsingError = ParsingError
parse.BufferError = BufferError
parse.parsing = parsing
parse.parsed = parsed
module.exports = parse
function parse(request, maxBuffer = Infinity, log = () => {}) {
if (request[parsing] !== undefined) return request[parsing]
const contentTypeDirectives = request.headers['content-type']
?.split(';')
.map(d => d.trim())
if (!contentTypeDirectives?.includes('application/json')) {
return Promise.reject(new ContentTypeError())
}
log('parsing')
const r = getStream(request, {maxBuffer}).then(
json => {
try {
const data = JSON.parse(json)
request[parsed] = data
log({data})
return data
} catch (e) {
return Promise.reject(new ParsingError())
}
},
e => {
if (e instanceof getStream.MaxBufferError) {
return Promise.reject(new BufferError())
}
return Promise.reject(e)
}
)
request[parsing] = r
return r
}