Skip to content

Instantly share code, notes, and snippets.

@mb8z
Last active October 2, 2018 14:54
Show Gist options
  • Save mb8z/7ac3a146801b49b0d84acf412004d6f7 to your computer and use it in GitHub Desktop.
Save mb8z/7ac3a146801b49b0d84acf412004d6f7 to your computer and use it in GitHub Desktop.
// Example file showing how to structure file responsible for API connection (with the use of `axios` library)
import axios from 'axios';
export class Fetch {
static type = {
singular: 'singular',
list: 'list',
};
constructor({ api }) {
this.api = api;
}
async request(method, path, options = {}) {
const { type, ...rest } = options;
const response = await this.api[method](path, rest);
if (type === Fetch.type.singular) {
// NOTE Possible transformation for singular response type
return response;
}
if (type === Fetch.type.list) {
// NOTE Possible transformation for list response type
return response;
}
return response;
}
}
export default {};
// NOTE Possible default headers
// const setDefaults = ({ language }) => {
// // axios.defaults.headers.common['Accept-Language'] = language;
// };
const transformResponse = (data) => {
if (!data) return data;
try {
const parsed = JSON.parse(data);
return parsed;
} catch (err) {
console.error('Failed while parsing response.', err);
}
return data;
};
const { API_URL, NODE_ENV } = process.env;
const create = () => {
if (NODE_ENV === 'production' && !API_URL) {
throw Error('Please specify the \'API_URL\' env var.');
}
const api = axios.create({
baseURL: API_URL,
transformResponse,
});
const fetch = new Fetch({ api });
// SomeModel
const SomeModel = {
list: () => fetch.request('get', '/some-model/', { type: Fetch.type.list }),
get: (id) => fetch.request('get', `/some-model/${id}/`, { type: Fetch.type.list }),
};
const endpoints = {
SomeModel,
};
return endpoints;
};
export default create;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment