From c652ac6a2cd23ef29f48465be09c2b674783e8e9 Mon Sep 17 00:00:00 2001 From: Adam Mathes Date: Sun, 15 Feb 2026 17:44:55 -0800 Subject: Vanilla JS (v3): Implement 3-pane layout, item fetching, reading, and testing --- frontend-vanilla/src/api.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 frontend-vanilla/src/api.ts (limited to 'frontend-vanilla/src/api.ts') diff --git a/frontend-vanilla/src/api.ts b/frontend-vanilla/src/api.ts new file mode 100644 index 0000000..c32299d --- /dev/null +++ b/frontend-vanilla/src/api.ts @@ -0,0 +1,29 @@ +export function getCookie(name: string): string | undefined { + const value = `; ${document.cookie}`; + const parts = value.split(`; ${name}=`); + if (parts.length === 2) return parts.pop()?.split(';').shift(); +} + +/** + * A wrapper around fetch that automatically includes the CSRF token + * for state-changing requests (POST, PUT, DELETE). + */ +export async function apiFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + const method = init?.method?.toUpperCase() || 'GET'; + const isStateChanging = ['POST', 'PUT', 'DELETE'].includes(method); + + const headers = new Headers(init?.headers || {}); + + if (isStateChanging) { + const token = getCookie('csrf_token'); + if (token) { + headers.set('X-CSRF-Token', token); + } + } + + return fetch(input, { + ...init, + headers, + credentials: 'include', // Ensure cookies are sent + }); +} -- cgit v1.2.3