@nxtedition/nxt-undici 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,79 @@
1
- module.exports = (dispatch) => (opts, handler) =>
2
- typeof opts.body !== 'function'
3
- ? dispatch(opts, handler)
4
- : Promise.resolve(opts.body({ signal: opts.signal })).then(
5
- (body) => dispatch({ ...opts, body }, handler),
6
- (err) => handler.onError(err),
7
- )
1
+ const { isStream } = require('../utils')
2
+
3
+ class Handler {
4
+ constructor(opts, { handler }) {
5
+ this.handler = handler
6
+ this.body = opts.body
7
+ this.error = null
8
+ this.abort = null
9
+
10
+ this.errorHandler = (err) => {
11
+ if (this.abort) {
12
+ this.abort(err)
13
+ } else {
14
+ this.error = err
15
+ }
16
+ }
17
+
18
+ this.body.on('error', this.errorHandler)
19
+ }
20
+
21
+ onConnect(abort) {
22
+ if (this.error) {
23
+ abort(this.error)
24
+ } else {
25
+ this.abort = abort
26
+ return this.onConnect(abort)
27
+ }
28
+ }
29
+
30
+ onUpgrade(statusCode, rawHeaders, socket) {
31
+ return this.handler.onUpgrade(statusCode, rawHeaders, socket)
32
+ }
33
+
34
+ onBodySent(chunk) {
35
+ return this.handler.onBodySent(chunk)
36
+ }
37
+
38
+ onRequestSent() {
39
+ return this.handler.onRequestSent()
40
+ }
41
+
42
+ onHeaders(statusCode, rawHeaders, resume, statusMessage) {
43
+ return this.handler.onHeaders(statusCode, rawHeaders, resume, statusMessage)
44
+ }
45
+
46
+ onData(chunk) {
47
+ return this.handler.onData(chunk)
48
+ }
49
+
50
+ onComplete(rawTrailers) {
51
+ this.body.off('error', this.errorHandler)
52
+ return this.handler.onComplete(rawTrailers)
53
+ }
54
+
55
+ onError(err) {
56
+ this.body.off('error', this.errorHandler)
57
+ return this.handler.onError(err)
58
+ }
59
+ }
60
+
61
+ function dispatchImpl(dispatch, opts, handler) {
62
+ if (typeof opts.body === 'function') {
63
+ Promise.resolve(opts.body({ signal: opts.signal })).then(
64
+ (body) => dispatchImpl({ ...opts, body }, handler),
65
+ (err) => handler.onError(err),
66
+ )
67
+ } else if (isStream(opts.body)) {
68
+ if (opts.method === 'GET' || opts.method === 'HEAD') {
69
+ opts.body.resume() // dump
70
+ dispatch({ ...opts, body: undefined }, new Handler(opts, { handler }))
71
+ } else {
72
+ dispatch(opts, new Handler(opts, { handler }))
73
+ }
74
+ } else {
75
+ dispatch(opts, handler)
76
+ }
77
+ }
78
+
79
+ module.exports = (dispatch) => (opts, handler) => dispatchImpl(dispatch, opts, handler)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nxtedition/nxt-undici",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
4
4
  "license": "MIT",
5
5
  "author": "Robert Nagy <robert.nagy@boffins.se>",
6
6
  "main": "lib/index.js",