Created
June 5, 2017 23:56
-
-
Save jacks205/ed03d236319712b046c8289db4448238 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
import { Observable } from 'rxjs' | |
import axios from 'axios' | |
const API_BASE = '.sampleserve.net/api/v1' | |
const SUB_DOMAIN = 'test' // TODO: Add to store for other lab subdomains | |
const PROTOCOL = 'http' | |
/** | |
* @param {Object} Headers for HTTP request. | |
* @return {Object} Headers with `Accept` and `Content-Type` added. | |
*/ | |
function fillRequestHeaders(requestHeaders) { | |
let headers = { | |
'Content-Type': 'application/json', | |
} | |
return { ...headers, ...requestHeaders } | |
} | |
/** | |
* Sends a request with the given parameters. | |
* @param {String} url Url for request. | |
* @param {String} params URL parameters for request. | |
* @param {Object} data Body data. | |
* @param {String} method HTTP Method. | |
* @param {Object} headers Any headers to be added to request. `Content-Type` by default. | |
* @return {Observable} Observable representing the request. | |
*/ | |
const fetchAPI = (url, params = {}, data = {}, method = 'get', headers = {}) => { | |
headers = fillRequestHeaders(headers); | |
method = method.toLowerCase() | |
let config = { | |
headers, | |
method, | |
url, | |
params, | |
data, | |
withCredentials: true, | |
timeout: __DEV__ ? 3500 : 5000 | |
} | |
let request = axios(config) | |
.then((response) => { | |
console.log(response) | |
return response | |
}) | |
console.log(config) | |
return Observable.fromPromise(request) | |
} | |
class _API { | |
get(url, params = {}, headers = {}) { | |
return fetchAPI(`${PROTOCOL}://${SUB_DOMAIN}${API_BASE}${url}`, params, {}, 'get', headers) | |
} | |
post(url, params = {}, data = {}, headers = {}) { | |
return fetchAPI(`${PROTOCOL}://${SUB_DOMAIN}${API_BASE}${url}`, params, data, 'post', headers) | |
} | |
} | |
const API = new _API() | |
export default API |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment