Skip to content

Instantly share code, notes, and snippets.

@pablohpsilva
Last active March 21, 2018 19:37
Show Gist options
  • Save pablohpsilva/5cc55256b2fd2ebabea4946447c162d5 to your computer and use it in GitHub Desktop.
Save pablohpsilva/5cc55256b2fd2ebabea4946447c162d5 to your computer and use it in GitHub Desktop.
Creating axios resources
import axios from "axios"
axios.defaults.headers.put['Content-Type'] = 'application/json';
axios.defaults.headers.post['Content-Type'] = 'application/json';
const getDefaultActions = () => ({
get: { method: 'GET' },
save: { method: 'POST' },
query: { method: 'GET' },
update: { method: 'PUT' },
remove: { method: 'DELETE' },
delete: { method: 'DELETE' }
})
const applyQueryStringsOnURL = (url, params) => {
const tokens = url
.match(/(:[a-zA-Z0-9])\w+/g)
return tokens
? tokens
.map(token => token.replace(':', ''))
.reduce((acc, token) => acc.replace(`:${token}`, params[token] || ''), url)
: url
}
const getAxiosMethod = (method = 'get') => axios[method.toLowerCase()]
const prepareBaseURL = (baseURL, url = '', params = {}) => {
const replacedUrlWithTokens = applyQueryStringsOnURL(url, params)
return `${base}${replacedUrlWithTokens}`
}
const createResourceFunction = (name, action, baseURL) => {
const axiosMethod = getAxiosMethod(action.method)
return {
[name]: (params = {}, extra = {}) => axiosMethod(
prepareBaseURL(baseURL, action.url, params),
params,
Object.assign({ headers: { 'Content-Type': 'application/json' } }, extra)
)
}
}
export const resource = (baseURL, customActions = {}, options) => {
const actions = Object.assign(
getDefaultActions(),
customActions
)
return Object.keys(actions)
.reduce((acc, key) => Object.assign(
acc,
createResourceFunction(key, actions[key], baseURL)
), {})
}
export default resource
/**
// HOW TO USE IT:
const baseURL = 'https://google.com'
const actions = {
test: { method: 'GET', url: '/' }
}
const googleResource = resource(baseURL, actions)
googleResource.test()
.then(res => console.log(res.log))
// default resources:
googleResource.get()
.then(res => console.log(res.log))
googleResource.save({ name: 'oi' })
.then(res => console.log(res.log))
googleResource.query({ id: 1 })
.then(res => console.log(res.log))
googleResource.update({ id: 1, name: 'hi' })
.then(res => console.log(res.log))
googleResource.remove({ id: 1 })
.then(res => console.log(res.log))
googleResource.delete({ id: 1 })
.then(res => console.log(res.log))
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment