unwrap-handler.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. rawHeaders = null
  12. rawTrailers = null
  13. constructor (abort) {
  14. this.#abort = abort
  15. }
  16. pause () {
  17. this.#paused = true
  18. }
  19. resume () {
  20. if (this.#paused) {
  21. this.#paused = false
  22. this[kResume]?.()
  23. }
  24. }
  25. abort (reason) {
  26. if (!this.#aborted) {
  27. this.#aborted = true
  28. this.#reason = reason
  29. this.#abort(reason)
  30. }
  31. }
  32. get aborted () {
  33. return this.#aborted
  34. }
  35. get reason () {
  36. return this.#reason
  37. }
  38. get paused () {
  39. return this.#paused
  40. }
  41. }
  42. module.exports = class UnwrapHandler {
  43. #handler
  44. #controller
  45. constructor (handler) {
  46. this.#handler = handler
  47. }
  48. static unwrap (handler) {
  49. // TODO (fix): More checks...
  50. return !handler.onRequestStart ? handler : new UnwrapHandler(handler)
  51. }
  52. onConnect (abort, context) {
  53. this.#controller = new UnwrapController(abort)
  54. this.#handler.onRequestStart?.(this.#controller, context)
  55. }
  56. onResponseStarted () {
  57. return this.#handler.onResponseStarted?.()
  58. }
  59. onUpgrade (statusCode, rawHeaders, socket) {
  60. this.#controller.rawHeaders = rawHeaders
  61. this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket)
  62. }
  63. onHeaders (statusCode, rawHeaders, resume, statusMessage) {
  64. this.#controller[kResume] = resume
  65. this.#controller.rawHeaders = rawHeaders
  66. this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage)
  67. return !this.#controller.paused
  68. }
  69. onData (data) {
  70. this.#handler.onResponseData?.(this.#controller, data)
  71. return !this.#controller.paused
  72. }
  73. onComplete (rawTrailers) {
  74. this.#controller.rawTrailers = rawTrailers
  75. this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers))
  76. }
  77. onError (err) {
  78. if (!this.#handler.onResponseError) {
  79. throw new InvalidArgumentError('invalid onError method')
  80. }
  81. this.#handler.onResponseError?.(this.#controller, err)
  82. }
  83. }