Skip to content

Instantly share code, notes, and snippets.

@caub
Created October 22, 2024 11:07
Show Gist options
  • Save caub/14439d39ef9adf14bdd5dc25a402ce18 to your computer and use it in GitHub Desktop.
Save caub/14439d39ef9adf14bdd5dc25a402ce18 to your computer and use it in GitHub Desktop.
Storeganise API helper for addons
export default function storeganiseApi({ apiUrl, addonId }) {
function fetchSg(path, {
method = 'GET',
body,
} = {}) {
const url = `${apiUrl}/v1/admin/${path}`;
return fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
Authorization: `Addon ${addonId}|${process.env.SG_API_KEY}`,
},
body: body && JSON.stringify(body),
})
.then(async response => {
const data = await response.json().catch(() => ({}));
if (!response.ok) {
console.error(`Error calling ${method} ${url}: ${response.status} ${response.statusText}`);
const err = Object.assign(new Error(), data.error);
err.status = response.status;
throw err;
}
return data;
});
}
return {
get(path, params) {
return fetchSg(path + (params ? `?${new URLSearchParams(params)}` : ''));
},
put(path, data = {}, params) {
return fetchSg(path + (params ? `?${new URLSearchParams(params)}` : ''), {
method: 'PUT',
body: data,
});
},
post(path, data = {}, params) {
return fetchSg(path + (params ? `?${new URLSearchParams(params)}` : ''), {
method: 'POST',
body: data,
});
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment