Skip to content

Instantly share code, notes, and snippets.

@laginha
Created October 7, 2019 10:56
Show Gist options
  • Save laginha/c71a3b2b343cc8b3f179b0d45bf91399 to your computer and use it in GitHub Desktop.
Save laginha/c71a3b2b343cc8b3f179b0d45bf91399 to your computer and use it in GitHub Desktop.
fetchJS wrapper to create resources and make requests
const request = (url, options) =>
fetch(url, {
'Content-Type': 'application/json',
...options
})
.then(response => {
if (response.ok) return response.json()
throw new Error(response.status)
})
const toQueryString = query =>
Object.entries(query)
.map((key, value) => `${key}=${value}`)
.join('&')
export const get = (url, data={}) => request(
`${url}?${toQueryString(data)}`
)
export const post = (url, data) => request(url, {
method: 'POST',
body: JSON.stringify(data)
})
export const createResource = path => ({
create: data => post(path, data),
index: query => get(path, query),
show: id => get(`${path}/${id}`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment