Files
famdone/frontend/src/routes/api/chat/+server.ts
T
2026-09-09 20:57:25 +01:00

45 lines
1.4 KiB
TypeScript

import { json, error } from '@sveltejs/kit';
import { createPbClient } from '$lib/server/pocketbase';
import { createServices, type ChatActor } from '$lib/server/services';
import type { RequestEvent } from '@sveltejs/kit';
type Body = {
action: 'send' | 'typing';
famId?: string;
content?: string;
clientId?: string;
typing?: boolean;
};
export async function POST(event: RequestEvent) {
const body = (await event.request.json().catch(() => null)) as Body | null;
if (!body || !body.action) return json({ error: 'missing action' }, { status: 400 });
const u = event.locals.user;
if (!u || !event.locals.pbToken) throw error(401, 'Unauthorized');
const pb = createPbClient(event.locals.pbToken);
const actor: ChatActor = {
id: u.id,
type: u.role === 'parent' ? 'admin' : 'member',
name: u.name,
color: u.color || '#6366f1'
};
const famId = body.famId || u.famId || '';
if (!famId) return json({ error: 'famId required' }, { status: 400 });
try {
const s = createServices(pb, { id: u.id, role: u.role });
const data =
body.action === 'typing'
? await s.chat.typing(famId, actor, { typing: Boolean(body.typing) })
: await s.chat.send(famId, actor, {
content: body.content || '',
clientId: body.clientId || '',
siteUrl: event.url.origin
});
return json(data);
} catch (e) {
return json({ error: e instanceof Error ? e.message : 'chat request failed' }, { status: 400 });
}
}