import { json, error } from '@sveltejs/kit'; import { createAirtableServices } from '$lib/airtable'; import type { RequestHandler } from './$types'; const apiKey = process.env.VITE_AIRTABLE_API_KEY; const baseId = process.env.VITE_AIRTABLE_BASE_ID; if (!apiKey || !baseId) { throw new Error('Airtable API key and base ID must be configured'); } const airtable = createAirtableServices(apiKey, baseId); // GET /api/settings - Get settings (assuming single settings record or by user) export const GET: RequestHandler = async ({ url }) => { try { const userId = url.searchParams.get('userId'); let filter = ''; if (userId) { filter = `{userId}="${userId}"`; } const response = await airtable.settings.listRecords(filter); const settings = response.records.map(record => ({ id: record.id, ...record.fields, // Parse JSON fields if they exist dashboardLayout: record.fields.dashboardLayout ? JSON.parse(record.fields.dashboardLayout) : null })); // Return first settings record if no userId specified, or all matching records return json(userId ? settings : settings[0] || null); } catch (err) { console.error('Error fetching settings:', err); throw error(500, 'Failed to fetch settings'); } }; // POST /api/settings - Create new settings export const POST: RequestHandler = async ({ request }) => { try { const settingsData = await request.json(); const fields = { ...settingsData, dashboardLayout: settingsData.dashboardLayout ? JSON.stringify(settingsData.dashboardLayout) : null }; const record = await airtable.settings.createRecord(fields); const settings = { id: record.id, ...record.fields, dashboardLayout: record.fields.dashboardLayout ? JSON.parse(record.fields.dashboardLayout) : null }; return json(settings, { status: 201 }); } catch (err) { console.error('Error creating settings:', err); throw error(500, 'Failed to create settings'); } };