|
- import { NextResponse } from 'next/server';
- import { revalidatePath } from 'next/cache'; // ADD THIS
- import { getPortals, savePortals } from '@/lib/db';
- import { isValidHexColor, sanitizeWelcomeText } from '@/lib/sanitize';
- import { validatePortal } from '@/lib/validation';
- import { Portal } from '@/types';
-
- export const dynamic = 'force-dynamic';
-
- export async function GET() {
- const portals = await getPortals();
- return NextResponse.json(portals[0] || null);
- }
-
- export async function POST(request: Request) {
- try {
- const incomingPortal: Portal = await request.json();
-
- // Sanifica l'HTML del welcome text prima di validare la lunghezza, così il counter
- // riflette il contenuto effettivamente persistito.
- if (typeof incomingPortal.welcomeText === 'string') {
- incomingPortal.welcomeText = sanitizeWelcomeText(incomingPortal.welcomeText);
- }
-
- const { valid, errors } = validatePortal(incomingPortal);
- if (!valid) {
- return NextResponse.json(
- { error: 'The portal settings could not be saved because some fields are invalid. See the highlighted errors and fix them, then try again.', errors },
- { status: 400 },
- );
- }
-
- // themeColor goes into a <style dangerouslySetInnerHTML> in PublicGrid,
- // so reject anything that is not a strict #RRGGBB.
- if (incomingPortal.themeColor !== undefined && !isValidHexColor(incomingPortal.themeColor)) {
- return NextResponse.json(
- {
- error: 'Invalid theme color: expected a hex code in the form #RRGGBB (e.g. #1e3a8a).',
- errors: [{ field: 'themeColor', message: 'Theme color must be a hex code like #RRGGBB.' }],
- },
- { status: 400 },
- );
- }
-
- const portals = await getPortals();
-
- if (portals.length > 0) {
- portals[0] = { ...portals[0], ...incomingPortal };
- } else {
- portals.push({ ...incomingPortal, id: 'default-portal', tenantId: 'default' });
- }
-
- await savePortals(portals);
-
- // Rivalida sia la home che il layout (il font @font-face è applicato nel layout root)
- revalidatePath('/', 'layout');
-
- return NextResponse.json(portals[0], { status: 200 });
- } catch {
- return NextResponse.json(
- { error: 'Unexpected error while saving the portal settings. The changes were not saved. Check the server logs and try again.' },
- { status: 500 },
- );
- }
- }
|