Skip to content

Instantly share code, notes, and snippets.

@js2me
Created October 31, 2018 11:24
Show Gist options
  • Save js2me/2dac654302ceca4d080dc2abede7c9ba to your computer and use it in GitHub Desktop.
Save js2me/2dac654302ceca4d080dc2abede7c9ba to your computer and use it in GitHub Desktop.
requestify module
import { BASE_URL } from 'api'
let abortableRequests = {}
const createRequest = (
method,
path,
{ body, successStatus, abortableKey } = {}
) => {
let request = new XMLHttpRequest()
if (abortableKey) {
if (abortableRequests[abortableKey]) {
abortableRequests[abortableKey].abort()
delete abortableRequests[abortableKey]
}
abortableRequests[abortableKey] = request
}
// promise.cancel = () => request.abort()
return new Promise((resolve, reject) => {
request.withCredentials = true
request.onreadystatechange = () => {
if (request.readyState === 4) {
if (request.status === (successStatus || 200)) {
try {
const data = JSON.parse(request.responseText)
resolve(data)
} catch (e) {
reject(e)
}
} else {
reject(request.statusText)
}
request = null
if (abortableKey) {
delete abortableRequests[abortableKey]
}
}
}
request.open(method.toUpperCase(), `${BASE_URL}${path}`, true)
if (body) {
if (typeof body === 'object') {
request.setRequestHeader(
'Content-Type',
'application/json;charset=UTF-8'
)
request.send(JSON.stringify(body))
}
request.send(body)
} else {
request.send()
}
})
}
const requestify = {
get: (path, options) => createRequest('get', path, options),
post: (path, options) => createRequest('post', path, options),
put: (path, options) => createRequest('put', path, options),
patсh: (path, options) => createRequest('patсh', path, options),
}
export default requestify
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment