Created
June 26, 2015 18:28
-
-
Save robwormald/36650458ac19773dbf51 to your computer and use it in GitHub Desktop.
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
/** | |
* RWHttp | |
* | |
* Base Class Used for making XHR/AJAX requests, uses the ES6 window.fetch API where available, or Github's polyfill. | |
*/ | |
import {fetch} from './network/RWFetch'; | |
import {RWHttpRequest} from './network/RWHttpRequest'; | |
import {RWHttpResponse} from './network/RWHttpResponse'; | |
import {RWHttpConfig} from './network/RWHttpConfig'; | |
import {HTTP_METHOD, HTTP_STATUS, isSuccessfulStatusCode} from './network/RWNetwork'; | |
export class RWHttp { | |
constructor(fetch: fetch, httpConfig: RWHttpConfig){ | |
this._fetch = fetch; | |
this._httpConfig = httpConfig; | |
} | |
_status (response) { | |
return isSuccessfulStatusCode(response.status) ? | |
Promise.resolve(response): | |
Promise.reject(response); | |
} | |
_sendRequest(request){ | |
return this._fetch(request.getUrl(), request.options) | |
.then((res) => this._status(res)); | |
} | |
setBaseUrl(baseUrl) { | |
this._httpConfig.baseURL = baseUrl; | |
} | |
get(url,options){ | |
return this._sendRequest(new RWHttpRequest(HTTP_METHOD.GET,url,options)) | |
.then(RWHttpResponse.get); | |
} | |
put(url,data,options){ | |
return this._sendRequest(new RWHttpRequest(HTTP_METHOD.PUT,url, options,data)) | |
.then(RWHttpResponse.get); | |
} | |
post(url,data,options){ | |
return this._sendRequest(new RWHttpRequest(HTTP_METHOD.POST, url, options, data)) | |
.then(RWHttpResponse.get); | |
} | |
delete(url,options){ | |
return this._sendRequest(new RWHttpRequest(HTTP_METHOD.DELETE, url, options)) | |
.then(RWHttpResponse.get); | |
} | |
postForm(url,formData,options){ | |
var request = new RWHttpRequest(HTTP_METHOD.POST, url, options); | |
request.setFormData(formData); | |
return this._sendRequest(request); | |
} | |
uploadFile(url, fileData, options){ | |
var request = new RWHttpRequest(HTTP_METHOD.POST, url, options); | |
request.setBody(fileData); | |
return this._sendRequest(request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment