unwrap-handler.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict'
  2. const { parseHeaders } = require('../core/util')
  3. const { InvalidArgumentError } = require('../core/errors')
  4. const kResume = Symbol('resume')
  5. class UnwrapController {
  6. #paused = false
  7. #reason = null
  8. #aborted = false
  9. #abort
  10. [kResume] = null
  11. constructor (abort) {
  12. this.#abort = abort
  13. }
  14. pause () {
  15. this.#paused = true
  16. }
  17. resume () {
  18. if (this.#paused) {
  19. this.#paused = false
  20. this[kResume]?.()
  21. }
  22. }
  23. abort (reason) {
  24. if (!this.#aborted) {
  25. this.#aborted = true
  26. this.#reason = reason
  27. this.#abort(reason)
  28. }
  29. }
  30. get aborted () {
  31. return this.#aborted
  32. }
  33. get reason () {
  34. return this.#reason
  35. }
  36. get paused () {
  37. return this.#paused
  38. }
  39. }
  40. module.exports = class UnwrapHandler {
  41. #handler
  42. #controller
  43. constructor (handler) {
  44. this.#handler = handler
  45. }
  46. static unwrap (handler) {
  47. // TODO (fix): More checks...
  48. return !handler.onRequestStart ? handler : new UnwrapHandler(handler)
  49. }
  50. onConnect (abort, context) {
  51. this.#controller = new UnwrapController(abort)
  52. this.#handler.onRequestStart?.(this.#controller, context)
  53. }
  54. onUpgrade (statusCode, rawHeaders, socket) {
  55. this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket)
  56. }
  57. onHeaders (statusCode, rawHeaders, resume, statusMessage) {
  58. this.#controller[kResume] = resume
  59. this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage)
  60. return !this.#controller.paused
  61. }
  62. onData (data) {
  63. this.#handler.onResponseData?.(this.#controller, data)
  64. return !this.#controller.paused
  65. }
  66. onComplete (rawTrailers) {
  67. this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers))
  68. }
  69. onError (err) {
  70. if (!this.#handler.onResponseError) {
  71. throw new InvalidArgumentError('invalid onError method')
  72. }
  73. this.#handler.onResponseError?.(this.#controller, err)
  74. }
  75. }