util.js 1.6 KB

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