Created
October 7, 2019 10:56
-
-
Save laginha/c71a3b2b343cc8b3f179b0d45bf91399 to your computer and use it in GitHub Desktop.
fetchJS wrapper to create resources and make requests
This file contains 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
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