Skip to content

Instantly share code, notes, and snippets.

@barbinbrad
Last active April 26, 2022 22:19
Show Gist options
  • Select an option

  • Save barbinbrad/258f68cd7276b33b5e25f7e77d6eb193 to your computer and use it in GitHub Desktop.

Select an option

Save barbinbrad/258f68cd7276b33b5e25f7e77d6eb193 to your computer and use it in GitHub Desktop.
REST API Client
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