Skip to content

Instantly share code, notes, and snippets.

@oleksmarkh
Last active August 15, 2020 09:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oleksmarkh/37c88570e0580ee47773eebbb0866c65 to your computer and use it in GitHub Desktop.
Save oleksmarkh/37c88570e0580ee47773eebbb0866c65 to your computer and use it in GitHub Desktop.
transport layer (abstraction over "axios")
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);
}
@oleksmarkh
Copy link
Author

oleksmarkh commented Sep 7, 2018

alternatives:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment