Skip to content

Instantly share code, notes, and snippets.

@jacks205
Created June 5, 2017 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacks205/ed03d236319712b046c8289db4448238 to your computer and use it in GitHub Desktop.
Save jacks205/ed03d236319712b046c8289db4448238 to your computer and use it in GitHub Desktop.
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