Skip to content

Instantly share code, notes, and snippets.

@flintinatux
Created November 4, 2016 05:32
Show Gist options
  • Save flintinatux/34ff8e28c65e91a8099d58411023861e to your computer and use it in GitHub Desktop.
Save flintinatux/34ff8e28c65e91a8099d58411023861e to your computer and use it in GitHub Desktop.
const identity = require('ramda/src/identity')
const qs = require('qs')
const Task = require('./task')
const parseHeaders = identity
const request = opts => Task((reject, resolve) => {
var {
data,
deserialize = identity,
headers = {},
json = false,
method = 'GET',
onUploadProgress,
serialize = identity,
url
} = opts
if (json) {
deserialize = JSON.parse
serialize = JSON.stringify
headers['Content-Type'] = 'application/json'
}
if (method === 'GET' && data) url = `${url}?${qs.stringify(data)}`
const xhr = new XMLHttpRequest()
xhr.addEventListener('error', reject)
xhr.addEventListener('load', () => {
resolve({
body: deserialize(xhr.response),
headers: parseHeaders(xhr.getResponseHeader('Content-Length')),
status: xhr.status
})
})
if (xhr.upload && typeof onUploadProgress === 'function')
xhr.upload.addEventListener('progress', onUploadProgress)
xhr.open(method, url)
for (var key in headers) xhr.setRequestHeader(key, headers[key])
if (method !== 'GET' && data) {
xhr.send(serialize(data))
} else {
xhr.send()
}
})
module.exports = request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment