ttf-api
Version:
The TrueToForm API SDK
111 lines (93 loc) • 3.1 kB
JavaScript
export const sessionIdKey = "ttf-analytics-session-id";
export const userIdKey = "ttf-analytics-user-id";
export const createClient = (apiKey) => {
const isDev =
process.env.NODE_ENV === "development" ||
window.location.hostname === "localhost" ||
window.location.origin === "https://truetoform-test-store.myshopify.com";
const baseUrl = isDev
? "https://api.truetoform.online/v1"
: "https://api.truetoform.fit/v1";
const getHeaders = () => {
const headers = {
"Content-Type": "application/json",
"X-TTF-API-KEY": apiKey,
};
const urlParams = new URLSearchParams(window.location.search);
const sessionId =
urlParams.get(sessionIdKey) || localStorage.getItem(sessionIdKey);
const userId = urlParams.get(userIdKey) || localStorage.getItem(userIdKey);
if (sessionId) {
headers["X-TTF-SESSION-ID"] = sessionId;
}
if (userId) {
headers["X-TTF-USER-ID"] = userId;
}
return headers;
};
const request = async (
method,
endpoint,
body = null,
signal = null,
eTag = null
) => {
const headers = getHeaders();
if (eTag) {
headers["If-None-Match"] = eTag;
}
const options = {
method,
headers,
body: body ? JSON.stringify(body) : null,
credentials: "include",
signal,
};
const response = await fetch(`${baseUrl}/${endpoint}`, options);
if (!response.ok && response.status !== 304) {
let errorMessage = response.statusText;
try {
const data = await response.json();
if (data?.message) {
errorMessage = data.message;
}
} catch (parseError) {
console.error("Failed to parse error response:", parseError);
}
throw new Error(`Error ${response.status}: ${errorMessage}`);
}
// Update session and user IDs from response headers
const newSessionId = response.headers.get("X-New-Session-ID");
const newUserId = response.headers.get("X-New-User-ID");
if (newSessionId) {
localStorage.setItem(sessionIdKey, newSessionId);
}
if (newUserId) {
localStorage.setItem(userIdKey, newUserId);
}
// Handle response body
if (response.status === 204) {
return null;
}
const contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
const data = await response.json();
return data;
} else if (contentType && contentType.includes("text/event-stream")) {
return response.body;
} else {
if (response.status === 304) {
return { currentETag: localStorage.getItem("ttf-sdk-eTag") };
}
const text = await response.text();
return text;
}
};
return {
get: (endpoint, signal, eTag) =>
request("GET", endpoint, null, signal, eTag),
post: (endpoint, body, signal) => request("POST", endpoint, body, signal),
put: (endpoint, body, signal) => request("PUT", endpoint, body, signal),
delete: (endpoint, signal) => request("DELETE", endpoint, null, signal),
};
};