Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Progress events without breaking pub-sub #60

Merged
merged 13 commits into from
Nov 13, 2020
Prev Previous commit
Next Next commit
fix: workaround electron-fetch issues
  • Loading branch information
Gozala committed Oct 13, 2020
commit 1a56843a63425e957be1df3ccf3f8a23db80b0ad
27 changes: 25 additions & 2 deletions src/http/fetch.node.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,37 @@ const withUploadProgress = (options) => {
* @returns {Readable}
*/
const bodyWithUploadProgress = (init, onUploadProgress) => {
// @ts-ignore - node-fetch is typed poorly
const { body } = new Response(init.body, init)
// This works around the fact that electron-fetch serializes `Uint8Array`s
// and `ArrayBuffer`'s to strings.
Gozala marked this conversation as resolved.
Show resolved Hide resolved
const content = normalizeBody(init.body)

// @ts-ignore - Response does not accept node `Readable` streams.
const { body } = new Response(content, init)
// @ts-ignore - Unlike standard Response, node-fetch `body` has a differnt
// type see: see https://github.com/node-fetch/node-fetch/blob/master/src/body.js
const source = iterateBodyWithProgress(body, onUploadProgress)
return toStream.readable(source)
}

/**
* @param {BodyInit} [input]
* @returns {Buffer|Readable|Blob|null}
*/
const normalizeBody = (input = null) => {
if (input instanceof ArrayBuffer) {
return Buffer.from(input)
} else if (ArrayBuffer.isView(input)) {
return Buffer.from(input.buffer, input.byteOffset, input.byteLength)
} else if (typeof input === 'string') {
return Buffer.from(input)
} else {
// @ts-ignore - Could be FormData|URLSearchParams|ReadableStream<Uint8Array>
// however electron-fetch does not support either of those types and
// node-fetch normalizes those to node streams.
return input
}
}

/**
* Takes body from native-fetch response as body and `onUploadProgress` handler
* and returns async iterable that emits body chunks and emits
Expand Down