Files
famdone/frontend/src/routes/chat/+server.ts
T
2026-08-10 17:28:02 +01:00

59 lines
1.8 KiB
TypeScript

import { json } from '@sveltejs/kit';
import { PROXY_URL } from '$app/env/public';
import type { RequestEvent } from '@sveltejs/kit';
const HONO_URL = PROXY_URL;
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' }, 400);
const session = event.locals.session;
const deviceToken = event.cookies.get('device_token') || '';
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
let famId = body.famId || '';
if (session?.famId && session?.userId) {
// Admin (parent) — trust the verified session server-side.
headers['x-session-famid'] = session.famId;
headers['x-session-userid'] = session.userId;
famId = session.famId;
} else if (deviceToken) {
// Member (child) — forward the device token; the proxy re-validates.
headers['x-device-token'] = deviceToken;
headers['x-device-famid'] = famId;
} else {
return json({ error: 'Unauthorized' }, 401);
}
if (!famId) return json({ error: 'famId required' }, 400);
const path = body.action === 'typing' ? `/api/chat/${famId}/typing` : `/api/chat/${famId}/messages`;
const payload =
body.action === 'typing'
? { typing: Boolean(body.typing) }
: { content: body.content || '', clientId: body.clientId || '' };
try {
const res = await fetch(`${HONO_URL}${path}`, {
method: 'POST',
headers,
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) return json({ error: data.error || 'chat request failed' }, res.status);
return json(data);
} catch {
return json({ error: 'chat request failed' }, 502);
}
}