Last active
October 2, 2018 14:54
-
-
Save mb8z/7ac3a146801b49b0d84acf412004d6f7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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