Created
August 2, 2020 03:45
-
-
Save Lucifier129/b9f8c585d81e502044d7ebc6b2097020 to your computer and use it in GitHub Desktop.
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
export const fetch = (url, options = {}) => { | |
let { fetch = globalThis.fetch, ...restOptions } = options; | |
if (typeof fetch !== 'function') { | |
throw new Error(`Expected fetch to be a function, but received ${fetch}`); | |
} | |
let finalUrl = url; | |
let finalOptions = { | |
credentials: 'include', | |
...restOptions | |
} | |
return fetch(finalUrl, finalOptions); | |
}; | |
export const post = (url, body, options) => { | |
return fetch(url, { | |
...options, | |
method: 'POST', | |
body: body, | |
}); | |
}; | |
export const get = (url, query, options) => { | |
let separator = url.includes('?') ? '&' : '?'; | |
let finalUrl = url + separator + querystring.stringify(query); | |
return fetch(finalUrl, { | |
...options, | |
method: 'GET', | |
}); | |
}; | |
const toJSON = (response, debug) => { | |
let text = await response.text(); | |
try { | |
return JSON.parse(text); | |
} catch (error) { | |
if (debug || process.env.NODE_ENV === 'development') { | |
console.log(`JSON parse failed, source: \n${text}`); | |
} | |
throw error; | |
} | |
} | |
export const getJSON = async (url, query, options = {}) => { | |
let { debug, ...restOptions } = options; | |
let response = await get(url, query, restOptions); | |
return toJSON(response, debug) | |
}; | |
export const postJSON = async (url, data, options = {}) => { | |
let { debug, ...restOptions } = options; | |
let finlaOptions = { | |
...restOptions, | |
headers: { | |
'Content-Type': 'application/json', | |
...restOptions.headers | |
} | |
} | |
let response = await post(url, JSON.stringify(data), finlaOptions) | |
return toJSON(response, debug) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment