Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import fetch from 'isomorphic-fetch'
  2.  
  3. const defaultHeaders = {
  4.   Accept: 'application/json',
  5.   'Content-Type': 'application/json',
  6. }
  7.  
  8. /**
  9.   * @return {Object} headers with token
  10.   */
  11. function buildHeaders() {
  12.   //const authToken = localStorage.getItem('we.token')
  13.   //return { ...defaultHeaders, Authorization: authToken }
  14.   return defaultHeaders
  15. }
  16.  
  17. /**
  18.   * @param {Object} response - standart isomorphic-fetch response object
  19.   * @return {Object} success isomorphic-fetch response
  20.   */
  21. export function checkStatus(response) {
  22.   let json = response.json() // http://stackoverflow.com/a/29475662/1916578
  23.  
  24.   if (response.status >= 200 && response.status < 300) {
  25.     return json
  26.   } else {
  27.     return json.then(window.Promise.reject.bind(window.Promise))
  28.   }
  29. }
  30.  
  31. /**
  32.   * @param {String} url - api request url
  33.   * @return {Object} fetch response (promise)
  34.   */
  35. export function httpGet(url) {
  36.   return fetch(url, {
  37.     headers: buildHeaders(),
  38.   })
  39.   .then(checkStatus)
  40. }
  41.  
  42. /**
  43.   * @param {String} url - api request url
  44.   * @return {Object} fetch response (promise)
  45.   */
  46. export function httpPost(url, data) {
  47.   const body = JSON.stringify(data)
  48.  
  49.   return fetch(url, {
  50.     method: 'post',
  51.     headers: buildHeaders(),
  52.     body: body,
  53.   })
  54.   .then(checkStatus)
  55. }
  56.  
  57. /**
  58.   * @param {String} url - api request url
  59.   * @return {Object} fetch response (promise)
  60.   */
  61. export function httpDelete(url) {
  62.  
  63.   return fetch(url, {
  64.     method: 'delete',
  65.     headers: buildHeaders(),
  66.   })
  67.   .then(checkStatus)
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement