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

feat: http upload/download progress handlers #54

Merged
merged 4 commits into from
Aug 12, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"dist"
],
"browser": {
"./src/http/fetch.js": "./src/http/fetch.browser.js",
"./src/text-encoder.js": "./src/text-encoder.browser.js",
"./src/text-decoder.js": "./src/text-decoder.browser.js",
"./src/temp-dir.js": "./src/temp-dir.browser.js",
Expand Down Expand Up @@ -63,4 +64,4 @@
"Irakli Gozalishvili <contact@gozala.io>",
"Marcin Rataj <lidel@lidel.org>"
]
}
}
23 changes: 4 additions & 19 deletions src/http.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,14 @@
/* eslint-disable no-undef */
'use strict'

const fetch = require('node-fetch')
const { fetch, Request, Headers } = require('./http/fetch')
const { TimeoutError, HTTPError } = require('./http/error')
const merge = require('merge-options').bind({ ignoreUndefined: true })
const { URL, URLSearchParams } = require('iso-url')
const TextDecoder = require('./text-decoder')
const AbortController = require('abort-controller')
const anySignal = require('any-signal')

const Request = fetch.Request
const Headers = fetch.Headers

class TimeoutError extends Error {
constructor () {
super('Request timed out')
this.name = 'TimeoutError'
}
}

class HTTPError extends Error {
constructor (response) {
super(response.statusText)
this.name = 'HTTPError'
this.response = response
}
}

const timeout = (promise, ms, abortController) => {
if (ms === undefined) {
return promise
Expand Down Expand Up @@ -87,6 +70,8 @@ const defaults = {
* @prop {function(URLSearchParams): URLSearchParams } [transformSearchParams]
* @prop {function(any): any} [transform] - When iterating the response body, transform each chunk with this function.
* @prop {function(Response): Promise<void>} [handleError] - Handle errors
* @prop {function({total:number, loaded:number, lengthComputable:boolean}):void} [onUploadProgress] - Can be passed to track upload progress (in browsers only).
achingbrain marked this conversation as resolved.
Show resolved Hide resolved
* @prop {function({total:number, loaded:number, lengthComputable:boolean}):void} [onDownloadProgress] - Can be passed to track download progress (in browsers only).
achingbrain marked this conversation as resolved.
Show resolved Hide resolved
*/

class HTTP {
Expand Down
26 changes: 26 additions & 0 deletions src/http/error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use strict'

class TimeoutError extends Error {
constructor (message = 'Request timed out') {
super(message)
this.name = 'TimeoutError'
}
}
exports.TimeoutError = TimeoutError

class AbortError extends Error {
constructor (message = 'The operation was aborted.') {
super(message)
this.name = 'AbortError'
}
}
exports.AbortError = AbortError

class HTTPError extends Error {
constructor (response) {
super(response.statusText)
this.name = 'HTTPError'
this.response = response
}
}
exports.HTTPError = HTTPError
124 changes: 124 additions & 0 deletions src/http/fetch.browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
'use strict'
/* eslint-env browser */

const { TimeoutError, AbortError } = require('./error')

/**
* @typedef {RequestInit & ExtraFetchOptions} FetchOptions
* @typedef {Object} ExtraFetchOptions
* @property {number} [timeout]
* @property {URLSearchParams} [searchParams]
* @property {function({total:number, loaded:number, lengthComputable:boolean}):void} [onUploadProgress]
* @property {function({total:number, loaded:number, lengthComputable:boolean}):void} [onDownloadProgress]
* @property {string} [overrideMimeType]
* @returns {Promise<Response>}
*/

/**
* @param {string|URL} url
* @param {FetchOptions} [options]
* @returns {Promise<Response>}
*/
const fetch = (url, options = {}) => {
const request = new XMLHttpRequest()
request.open(options.method || 'GET', url.toString(), true)

const { timeout } = options
if (timeout > 0 && timeout < Infinity) {
request.timeout = options.timeout
}

if (options.overrideMimeType != null) {
request.overrideMimeType(options.overrideMimeType)
}

if (options.headers) {
for (const [name, value] of options.headers.entries()) {
request.setRequestHeader(name, value)
}
}

if (options.signal) {
options.signal.onabort = () => request.abort()
}

if (options.onDownloadProgress) {
request.onprogress = options.onDownloadProgress
}

if (options.onUploadProgress) {
request.upload.onprogress = options.onUploadProgress
}

return new Promise((resolve, reject) => {
/**
* @param {Event} event
*/
const handleEvent = (event) => {
switch (event.type) {
case 'error': {
resolve(Response.error())
break
}
case 'load': {
resolve(
new ResponseWithURL(request.responseURL, request.response, {
status: request.status,
statusText: request.statusText,
headers: parseHeaders(request.getAllResponseHeaders())
})
)
break
}
case 'timeout': {
reject(new TimeoutError())
break
}
case 'abort': {
reject(new AbortError())
break
}
default: {
break
}
}
}
request.onerror = handleEvent
request.onload = handleEvent
request.ontimeout = handleEvent
request.onabort = handleEvent

request.send(options.body)
})
}
exports.fetch = fetch
exports.Request = Request
exports.Headers = Headers

/**
* @param {string} input
* @returns {Headers}
*/
const parseHeaders = (input) => {
const headers = new Headers()
for (const line of input.trim().split(/[\r\n]+/)) {
const index = line.indexOf(': ')
if (index > 0) {
headers.set(line.slice(0, index), line.slice(index + 1))
}
}

return headers
}

class ResponseWithURL extends Response {
/**
* @param {string} url
* @param {string|Blob|ArrayBufferView|ArrayBuffer|FormData|ReadableStream<Uint8Array>} body
* @param {ResponseInit} options
*/
constructor (url, body, options) {
super(body, options)
Object.defineProperty(this, 'url', { value: url })
}
}
12 changes: 12 additions & 0 deletions src/http/fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
'use strict'

// Electron has `XMLHttpRequest` and should get the browser implementation
// instead of node.
if (typeof XMLHttpRequest !== 'undefined') {
module.exports = require('./fetch.browser')
} else {
const fetch = require('node-fetch')
exports.fetch = fetch
exports.Request = fetch.Request
exports.Headers = fetch.Headers
}
25 changes: 25 additions & 0 deletions test/http.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,29 @@ describe('http', function () {

await expect(drain(HTTP.ndjson(res.body))).to.eventually.be.rejectedWith(/aborted/)
})

;(typeof XMLHttpRequest === 'undefined' ? it.skip : it)('progress events', async () => {
let upload = 0
let download = 0
const body = new Uint8Array(1000000 / 2)
const request = await HTTP.post(`${process.env.ECHO_SERVER}/echo`, {
body,
onUploadProgress: (progress) => {
expect(progress).to.have.property('lengthComputable').to.be.a('boolean')
expect(progress).to.have.property('total', body.byteLength)
expect(progress).to.have.property('loaded').to.be.a('number')
upload += 1
},
onDownloadProgress: (progress) => {
expect(progress).to.have.property('lengthComputable').to.be.a('boolean')
expect(progress).to.have.property('total').to.be.a('number')
expect(progress).to.have.property('loaded').to.be.a('number')
download += 1
}
})
await all(request.iterator())

expect(upload).to.be.greaterThan(0)
expect(download).to.be.greaterThan(0)
})
})