Skip to content

Instantly share code, notes, and snippets.

@robwormald
Created June 26, 2015 18:28
Show Gist options
  • Save robwormald/36650458ac19773dbf51 to your computer and use it in GitHub Desktop.
Save robwormald/36650458ac19773dbf51 to your computer and use it in GitHub Desktop.
/**
* 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