diff --git a/src/api/api.js b/src/api/api.js new file mode 100644 index 0000000..b5d3697 --- /dev/null +++ b/src/api/api.js @@ -0,0 +1,56 @@ +function getHeaders() { + const headers = new Headers(); + headers.append("Accept", "application/json"); + headers.append("Content-Type", "application/json"); + return headers; +} + +function internalFetch(url, options) { + return fetch(url, options).then((res) => + res.text().then((text) => { + let t = text ? JSON.parse(text) : res.statusText; + if (!res.ok) { + if (res.status === 404) throw new Error(t || "Not found"); + + if (res.status >= 400 && res.status < 600 && t) throw t; + + throw new Error(t || "Unknown error"); + } + return t; + }) + ); +} + +export function post(url, body) { + const options = { + method: "POST", + body: JSON.stringify(body), + headers: getHeaders() + }; + return internalFetch(url, options); +} + +export function put(url, body) { + const options = { + method: "PUT", + body: JSON.stringify(body), + headers: getHeaders() + }; + return internalFetch(url, options); +} + +export function get(url) { + const options = { + method: "GET", + headers: getHeaders() + }; + return internalFetch(url, options); +} + +export function del(url) { + const options = { + method: "DELETE", + headers: getHeaders() + }; + return internalFetch(url, options); +} diff --git a/src/features/system/api.js b/src/features/system/api.js index f0bdeea..9f2058b 100644 --- a/src/features/system/api.js +++ b/src/features/system/api.js @@ -1,14 +1,9 @@ -import { handleResponse, handleError } from "../../api/apiUtils"; +import { get } from "../../api/api"; const baseUrl = process.env.REVERSE_PROXY_API_URL + "/system"; -const getSystemDateTime = () => - fetch(`${baseUrl}/datetime`).then(handleResponse).catch(handleError); - -const getSystemVersion = () => - fetch(`${baseUrl}/version`).then(handleResponse).catch(handleError); - -const getReleaseNotes = () => - fetch(`${baseUrl}/release-notes`).then(handleResponse).catch(handleError); +const getSystemDateTime = () => get(`${baseUrl}/datetime`); +const getSystemVersion = () => get(`${baseUrl}/version`); +const getReleaseNotes = () => get(`${baseUrl}/release-notes`); export default { getSystemDateTime,