Created
November 4, 2016 05:32
-
-
Save flintinatux/34ff8e28c65e91a8099d58411023861e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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