import { v7 as uuidv7, type UUIDTypes } from 'uuid'; export interface User { email: string; name: string; subscription: boolean; } export interface Reaction { slug: string, browser_id: UUIDTypes } const API_BASE = import.meta.env.PUBLIC_API_URL; export const AUTH_TOKEN_KEY = 'authToken' export const USER_KEY = 'user' export const BROWSER_ID = 'browser_id' class BlauwasserAPI { private async fetchAPI( endpoint: string, options: RequestInit = {} ): Promise { const url = new URL(endpoint, API_BASE); const defaultHeaders: HeadersInit = { 'Content-Type': 'application/json', }; if (typeof window !== 'undefined') { const jwt = localStorage.getItem(AUTH_TOKEN_KEY); if (jwt) { defaultHeaders['Authorization'] = `Bearer ${jwt}`; } } const response = await fetch(url, { ...options, headers: { ...defaultHeaders, ...options.headers }, }); if (!response.ok) { throw new Error(`API Error ${response.status}: ${response.statusText}`); } return response.json(); } async getUserInfo(): Promise { return this.fetchAPI(`/users/me`); } async register(user: User): Promise { return this.fetchAPI(`/users`, { method: 'POST', body: JSON.stringify(user) }) } async login(userCode: string): Promise { const formData = new URLSearchParams(); formData.append('user_code', userCode); return await this.fetchAPI('/users/login', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData, }); } async toggleSubscription(subscription: boolean): Promise { const formData = new URLSearchParams(); formData.append('subscription', JSON.stringify(subscription)); return await this.fetchAPI('/users/me/subscription', { method: 'PUT', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData, }); } async deleteUser(): Promise { return await this.fetchAPI('/users/me', { method: "DELETE" }) } async approveNewsletter(secret: string): Promise { const formData = new URLSearchParams(); formData.append('secret', JSON.stringify(secret)); return await this.fetchAPI('/newsletter/approve', { method: 'POST', body: formData }) } async createReaction(reaction: Reaction): Promise { return await this.fetchAPI('/reactions', { method: 'POST', body: JSON.stringify(reaction) }) } async deleteReaction(reaction: Reaction): Promise { return await this.fetchAPI('/reactions', { method: 'DELETE', body: JSON.stringify(reaction) }) } async reactionCount(slug: string): Promise { return await this.fetchAPI(`/reactions/${slug}`, { method: 'GET' }) } async haveIReacted(reaction: Reaction): Promise { return await this.fetchAPI(`/reactions/?slug=${reaction.slug}&browser_id=${reaction.browser_id}`, {method: 'GET'}) } } export const api = new BlauwasserAPI();