fluxai-sdk
Version:
FluxAI JavaScript SDK for A/B experiment routing
54 lines (53 loc) • 2.43 kB
JavaScript
// src/index.mts
/**
* Checks if a given end-user should enter a specific experiment.
* Sends request to FluxAI backend's /should-enter endpoint using the provided API key.
*
* @param {ShouldEnterParams} params - Parameters for the experiment entry check.
* @returns {Promise<{ allow: boolean | null, reason?: string, user_attributes?: Record<string, any>, allowed_conditions?: Record<string, any> }>}
*/
export async function routecheck({ experiment, userId, attributes = {}, apiKey, }) {
if (!apiKey) {
console.error("FluxAI SDK Error: API Key is missing.");
return { allow: null, reason: "API Key is missing." };
}
// --- MODIFICATION: Move apiKey into the payload body ---
const payload = {
experiment_name: experiment,
user_id: userId,
attributes: attributes ?? {},
apiKey: apiKey, // <<< API KEY IS NOW PART OF THE BODY PAYLOAD
};
// --- END MODIFICATION ---
console.log("📤 FluxAI SDK Payload:", payload);
console.log("🔑 Using API Key (first 8 chars):", apiKey.substring(0, 8) + "...");
try {
const res = await fetch("https://api.get-fluxai.com/should-enter", {
method: "POST",
headers: {
"Content-Type": "application/json",
// --- MODIFICATION: REMOVE X-API-KEY HEADER ---
// "X-API-Key": apiKey, // <<< REMOVED THIS LINE
// --- END MODIFICATION ---
},
body: JSON.stringify(payload),
// mode: "cors", // No change needed, default for cross-origin is "cors"
// credentials: "omit", // No change needed for X-API-Key, but can be added if desired for other credentials
});
const data = await res.json();
if (!res.ok) {
console.error(`⚠️ FluxAI SDK API Error (${res.status}):`, data.detail || data.reason || 'Unknown error');
return { allow: null, reason: data.detail || data.reason || `API Error: ${res.status}` };
}
return {
allow: data?.allow ?? null,
reason: data?.reason,
user_attributes: data?.user_attributes,
allowed_conditions: data?.allowed_conditions,
};
}
catch (err) {
console.error("⚠️ FluxAI SDK Network Error:", err);
return { allow: null, reason: `Network error: ${err.message || 'Unknown network issue'}` };
}
}