Last active
February 13, 2018 16:55
-
-
Save pixelass/4bee23b3061ace0c7185629fb4e53cfc to your computer and use it in GitHub Desktop.
fetch.js
This file contains hidden or 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
class Ajax { | |
constructor(opts) { | |
this.callbacks = {} | |
this.on = this.on.bind(this) | |
this.fetch = this.fetch.bind(this) | |
this.error = this.error.bind(this) | |
this.data = this.data.bind(this) | |
this.complete = this.complete.bind(this) | |
return {...this.methods} | |
} | |
/** | |
* allow chaning mehtods by returning thes | |
* | |
* @return {{on: function, fetch: function}} | |
* public mehtods | |
*/ | |
get methods() { | |
return { | |
on: this.on.bind(this), | |
fetch: this.fetch.bind(this) | |
} | |
} | |
/** | |
* Transform response headers to an object | |
* | |
* @param {Header} headers | |
* The headers | |
* @return {Array} | |
*/ | |
responseHeaders(headers) { | |
return [...headers.entries()] | |
.reduce((previous, [key, value]) => | |
({...previous, [key]: value}), {} ) | |
} | |
fetch(url, options) { | |
fetch(url, options).then(response => { | |
this.callbacks.data(response.blob()) | |
this.callbacks.complete({ | |
headers: this.responseHeaders(response.headers), | |
statusCode: response.status | |
}) | |
}).catch(err => this.callbacks.error(err)) | |
return this | |
} | |
error(fn) { | |
this.callbacks.error = fn | |
} | |
data(fn) { | |
this.callbacks.data = fn | |
} | |
complete(fn) { | |
this.callbacks.complete = fn | |
} | |
on(e, fn) { | |
switch(e) { | |
case 'error': | |
this.error(fn) | |
break | |
case 'data': | |
this.data(fn) | |
break | |
case 'complete': | |
this.complete(fn) | |
break | |
default: | |
break | |
} | |
return this | |
} | |
} | |
export default function (options) { | |
return new Ajax(options) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment