• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1const assert = require('assert')
2const {
3  ResponseStatusCodeError
4} = require('../core/errors')
5const { toUSVString } = require('../core/util')
6
7async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
8  assert(body)
9
10  let chunks = []
11  let limit = 0
12
13  for await (const chunk of body) {
14    chunks.push(chunk)
15    limit += chunk.length
16    if (limit > 128 * 1024) {
17      chunks = null
18      break
19    }
20  }
21
22  if (statusCode === 204 || !contentType || !chunks) {
23    process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
24    return
25  }
26
27  try {
28    if (contentType.startsWith('application/json')) {
29      const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
30      process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
31      return
32    }
33
34    if (contentType.startsWith('text/')) {
35      const payload = toUSVString(Buffer.concat(chunks))
36      process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
37      return
38    }
39  } catch (err) {
40    // Process in a fallback if error
41  }
42
43  process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
44}
45
46module.exports = { getResolveErrorBodyCallback }
47