Last active
April 26, 2022 22:19
-
-
Save barbinbrad/258f68cd7276b33b5e25f7e77d6eb193 to your computer and use it in GitHub Desktop.
REST API Client
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
| const http = { | |
| stream(url) { | |
| return http.fetchBlob(url); | |
| }, | |
| get(url) { | |
| return http.fetchJson(url); | |
| }, | |
| post(url, data) { | |
| return http.fetchJson(url, { | |
| body: JSON.stringify(data), | |
| method: 'POST', | |
| }); | |
| }, | |
| delete(url, data) { | |
| return http.fetchJson(url, { | |
| body: JSON.stringify(data), | |
| method: 'DELETE', | |
| }); | |
| }, | |
| patch(url, data) { | |
| return http.fetchJson(url, { | |
| body: JSON.stringify(data), | |
| method: 'PATCH', | |
| }); | |
| }, | |
| fetchBlob(url) { | |
| const options = defaultOptions; | |
| return new Promise((resolve, reject) => { | |
| http | |
| .fetch(url, options) | |
| .then((response) => { | |
| if (response.ok) { | |
| return response | |
| .blob() | |
| .then((blob) => resolve(blob)) | |
| .catch(reject); | |
| } else { | |
| reject(response.statusText); | |
| } | |
| }) | |
| .catch((err) => { | |
| reject(err); | |
| }); | |
| }); | |
| }, | |
| fetchJson(url, params = {}) { | |
| const options = { | |
| ...defaultJsonOptions, | |
| ...params, | |
| }; | |
| return new Promise((resolve, reject) => { | |
| http | |
| .fetch(url, options) | |
| .then((response) => { | |
| if (response.ok) { | |
| return response | |
| .json() | |
| .then((json) => resolve(json)) | |
| .catch((err) => reject(err)); | |
| } else { | |
| reject(response.statusText); | |
| } | |
| }) | |
| .catch((err) => { | |
| reject(err); | |
| }); | |
| }); | |
| }, | |
| async fetch(url, options) { | |
| options.headers = { | |
| ...options.headers, | |
| ...(await getAuthorization()), | |
| }; | |
| // native call | |
| return fetch(url, options); | |
| }, | |
| }; | |
| export async function getAuthorization() { | |
| try { | |
| const jwt = 'TEMPORARY'; | |
| // const data = await Auth.currentSession(); | |
| // const jwt = data.getAccessToken().getJwtToken(); | |
| return { | |
| authorization: `Bearer ${jwt}`, | |
| }; | |
| } catch { | |
| return {}; | |
| } | |
| } | |
| const defaultOptions = { | |
| // credentials: 'same-origin', | |
| mode: 'cors', | |
| cache: 'no-store', | |
| }; | |
| const defaultJsonOptions = { | |
| // credentials: 'same-origin', | |
| headers: { | |
| Accept: 'application/json', | |
| 'Content-Type': 'application/json; charset=utf-8', | |
| }, | |
| mode: 'cors', | |
| cache: 'no-store', | |
| }; | |
| export default http; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment