Skip to content

Instantly share code, notes, and snippets.

@hpieroni
Last active February 6, 2023 15:25
Show Gist options
  • Save hpieroni/4c5e52cc3fbf62b371fad93f6f50f1ca to your computer and use it in GitHub Desktop.
Save hpieroni/4c5e52cc3fbf62b371fad93f6f50f1ca to your computer and use it in GitHub Desktop.
Fetch wrapper for json APIs
import { authService } from "../services";
import { fetchJSON } from "./fetch-json";
const BASE_URL = 'https://example.com';
function call(path, options = {}) {
const url = `${BASE_URL}/${path}`;
const token = authService.getToken();
if (token) {
options.headers = {
Authorization: `Bearer ${token}`
};
}
return fetchJSON(url, options).catch(error => {
if (error.status === 401) {
authService.logout();
}
return Promise.reject(error);
});
}
function get(path) {
return call(path, { method: "GET" });
}
function post(path, body) {
return call(path, { method: "POST", body });
}
function patch(path, body) {
return call(path, { method: "PATCH", body });
}
function put(path, body) {
return call(path, { method: "PUT", body });
}
function remove(path) {
return call(path, { method: "DELETE" });
}
export const api = { call, get, post, patch, put, remove };
const defaultMessage = ({ status, statusText }) =>
statusText || `${status} error code occurred`;
export async function fetchJSON(url, options = {}) {
const headers = {
Accept: "application/json",
"Content-Type": "application/json"
};
options.headers = options.headers
? {
...headers,
...options.headers
}
: headers;
if (options.body) {
options.body = JSON.stringify(options.body);
}
const response = await fetch(url, options);
try {
const json = await response.json();
return response.ok
? json
: Promise.reject({
...json,
status: json.status || response.status,
message: json.message || defaultMessage(response)
});
} catch (error) {
// In case the response does not have a JSON body, return a default one
return response.ok
? {}
: Promise.reject({
status: response.status,
message: defaultMessage(response)
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment