-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathparse-ring-json-responses.js
45 lines (33 loc) · 1.22 KB
/
parse-ring-json-responses.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
'use strict'
const contentType = require( 'content-type' )
const jsonBigIntParse = require( 'json-bigint' )({ storeAsString: true }).parse
const propagatedError = require( './propagated-error' )
const isJson = headers => {
try {
const contentTypeHeader = headers[ 'content-type' ]
if ( !contentTypeHeader ) {
return false
}
const type = ( contentType.parse( contentTypeHeader )).type
return ( type === 'application/json' )
} catch ( e ) {
throw propagatedError( 'could not tell if response is json', e )
}
}
module.exports = ( responseBody, headers ) => {
if ( isJson( headers )) {
try {
// Some of the ring endpoints return an empty response (but not a 204 status code)
// while claiming to be JSON. In this case, trying to parse the empty string as
// json will fail. To avoid the failure, return an empty object
if ( !responseBody.length ) {
return {}
}
return jsonBigIntParse( responseBody )
} catch ( e ) {
throw propagatedError( `invalid json in response: ${responseBody}`, e )
}
} else {
return responseBody
}
}