Last active
August 15, 2020 09:21
-
-
Save oleksmarkh/37c88570e0580ee47773eebbb0866c65 to your computer and use it in GitHub Desktop.
transport layer (abstraction over "axios")
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 axios from 'axios'; | |
import { mapKeys, mapValues, camelCase, snakeCase } from 'lodash'; | |
const { API_URL } = process.env; | |
function getAccessToken() { | |
// @todo: load access token from cookie | |
return 'token'; | |
} | |
function transformKeys(data, iteratee) { | |
if (Array.isArray(data)) { | |
return data.map((d) => transformKeys(d, iteratee)); | |
} | |
if (data instanceof Object) { | |
return mapValues( | |
mapKeys(data, (_, k) => iteratee(k)), | |
(v) => transformKeys(v, iteratee) | |
); | |
} | |
return data; | |
} | |
export function camelCaseKeys(data) { | |
return transformKeys(data, camelCase); | |
} | |
export function snakeCaseKeys(data) { | |
return transformKeys(data, snakeCase); | |
} | |
// @see: https://github.com/mzabriskie/axios#axios-api | |
export function request(method, url, config = {}, options = {}) { | |
const { | |
params, | |
data, | |
headers, | |
maxContentLength | |
} = config; | |
// non-axios specific params | |
const { | |
suppressAuth | |
} = options; | |
const baseURL = API_URL; | |
// @see: https://tools.ietf.org/html/rfc6750 | |
const bearerToken = `Bearer ${getAccessToken()}`; | |
return new Promise((resolve, reject) => { | |
axios({ | |
method, | |
baseURL, | |
url, | |
params, | |
data: snakeCaseKeys(data), | |
headers: suppressAuth ? headers : { ...headers, Authorization: bearerToken }, | |
maxContentLength | |
}) | |
.then((response) => { | |
resolve({ | |
...response, | |
data: camelCaseKeys(response.data) | |
}); | |
}) | |
.catch(reject); | |
}); | |
} | |
export function get(url, config, options) { | |
return request('GET', url, config, options); | |
} | |
export function post(url, config, options) { | |
return request('POST', url, config, options); | |
} | |
export function put(url, config, options) { | |
return request('PUT', url, config, options); | |
} | |
// not "delete()" because of reserved word | |
export function destroy(url, config, options) { | |
return request('DELETE', url, config, options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alternatives:
ky
- a wrapper over nativefetch()
API, a polyfill needed for older browsers