import {EventPostSchema} from "../schemas/eventPostSchema"; // Service responsible for sending event POST requests to the API. // - Validates and coerces the outgoing payload using EventPostSchema // - Logs validation errors (if any) and the final payload sent // - Sends the request with CSRF token (if available) and returns parsed JSON response const API_BASE = import.meta.env.VITE_API_BASE function getCSRFToken() { const name = "csrftoken"; const match = document.cookie.match(new RegExp('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')); return match ? match.pop() : null; } export default class EventService { constructor(base = API_BASE) { this.base = base; } async createEvent(rawPayload) { // Validate and coerce the outgoing payload const parsed = EventPostSchema.parse(rawPayload); // will throw if invalid console.log("EventService sending payload:", JSON.stringify(rawPayload, null, 2)); // Log here const res = await fetch(`${this.base}/event`, { method: "POST", headers: { "Content-Type": "application/json", // X-CSRFToken if using django session auth in browser ...(getCSRFToken() ? {"X-CSRFToken": getCSRFToken()} : {}), }, credentials: "same-origin", // change to 'include' if cross-site cookies body: JSON.stringify(parsed), }); if (!res.ok) { const text = await res.text(); const err = new Error("Failed to create event"); err.status = res.status; err.body = text; throw err; } return res.json(); } }