Debian Codegraph @

lib/dispatcher/dispatcher1-wrapper.js

raw
1 'use strict'
2
3 const Dispatcher = require('./dispatcher')
4 const { InvalidArgumentError } = require('../core/errors')
5 const { toRawHeaders } = require('../core/util')
6
7 class LegacyHandlerWrapper {
8 #handler
9
10 constructor (handler) {
11 this.#handler = handler
12 }
13
14 onRequestStart (controller, context) {
15 this.#handler.onConnect?.((reason) => controller.abort(reason), context)
16 }
17
18 onRequestUpgrade (controller, statusCode, headers, socket) {
19 const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {})
20 this.#handler.onUpgrade?.(statusCode, rawHeaders, socket)
21 }
22
23 onResponseStart (controller, statusCode, headers, statusMessage) {
24 const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {})
25
26 if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
27 controller.pause()
28 }
29 }
30
31 onResponseData (controller, chunk) {
32 if (this.#handler.onData?.(chunk) === false) {
33 controller.pause()
34 }
35 }
36
37 onResponseEnd (controller, trailers) {
38 const rawTrailers = controller?.rawTrailers ?? toRawHeaders(trailers ?? {})
39 this.#handler.onComplete?.(rawTrailers)
40 }
41
42 onResponseError (_controller, err) {
43 if (!this.#handler.onError) {
44 throw err
45 }
46
47 this.#handler.onError(err)
48 }
49
50 onBodySent (chunk) {
51 this.#handler.onBodySent?.(chunk)
52 }
53
54 onRequestSent () {
55 this.#handler.onRequestSent?.()
56 }
57
58 onResponseStarted () {
59 this.#handler.onResponseStarted?.()
60 }
61 }
62
63 class Dispatcher1Wrapper extends Dispatcher {
64 #dispatcher
65
66 constructor (dispatcher) {
67 super()
68
69 if (!dispatcher || typeof dispatcher.dispatch !== 'function') {
70 throw new InvalidArgumentError('Argument dispatcher must implement dispatch')
71 }
72
73 this.#dispatcher = dispatcher
74 }
75
76 static wrapHandler (handler) {
77 if (!handler || typeof handler !== 'object') {
78 throw new InvalidArgumentError('handler must be an object')
79 }
80
81 if (typeof handler.onRequestStart === 'function') {
82 return handler
83 }
84
85 return new LegacyHandlerWrapper(handler)
86 }
87
88 dispatch (opts, handler) {
89 // Legacy (v1) consumers do not support HTTP/2, so force HTTP/1.1.
90 // See https://github.com/nodejs/undici/issues/4989
91 if (opts.allowH2 !== false) {
92 opts = { ...opts, allowH2: false }
93 }
94
95 return this.#dispatcher.dispatch(opts, Dispatcher1Wrapper.wrapHandler(handler))
96 }
97
98 close (...args) {
99 return this.#dispatcher.close(...args)
100 }
101
102 destroy (...args) {
103 return this.#dispatcher.destroy(...args)
104 }
105 }
106
107 module.exports = Dispatcher1Wrapper