Last active
April 3, 2018 16:24
-
-
Save sportluffi/8714ce0a54e747ae4bda4e1fc904fa0d to your computer and use it in GitHub Desktop.
This file contains 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 HttpError from './HttpError'; | |
import { stringify } from 'query-string'; | |
export const fetchJson = (url, options = {}) => { | |
const requestHeaders = | |
options.headers || | |
new Headers({ | |
Accept: 'application/json', | |
}); | |
const token = localStorage.getItem('token'); | |
requestHeaders.set('Authorization', `Bearer ${token}`); | |
if ( | |
!requestHeaders.has('Content-Type') && | |
!(options && options.body && options.body instanceof FormData) | |
) { | |
requestHeaders.set('Content-Type', 'application/json'); | |
} | |
return fetch(url, { ...options, headers: requestHeaders }) | |
.then(response => | |
response.text().then(text => ({ | |
status: response.status, | |
statusText: response.statusText, | |
headers: response.headers, | |
body: text, | |
})) | |
) | |
.then(({ status, statusText, headers, body }) => { | |
let json; | |
try { | |
json = JSON.parse(body); | |
} catch (e) { | |
// not json | |
} | |
if (status < 200 || status >= 300) { | |
return Promise.reject( | |
new HttpError( | |
(json && json.message) || statusText, | |
status, | |
json | |
) | |
); | |
} | |
return { status, headers, body, json }; | |
}); | |
}; | |
export const queryParameters = stringify; | |
const isValidObject = value => { | |
if (!value) { | |
return false; | |
} | |
const isArray = Array.isArray(value); | |
const isBuffer = Buffer.isBuffer(value); | |
const isObject = | |
Object.prototype.toString.call(value) === '[object Object]'; | |
const hasKeys = !!Object.keys(value).length; | |
return !isArray && !isBuffer && isObject && hasKeys; | |
}; | |
export const flattenObject = (value, path = []) => { | |
if (isValidObject(value)) { | |
return Object.assign( | |
{}, | |
...Object.keys(value).map(key => | |
flattenObject(value[key], path.concat([key])) | |
) | |
); | |
} else { | |
return path.length ? { [path.join('.')]: value } : value; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment