NeahNew/app/api/notifications/route.ts
2025-05-05 13:04:01 +02:00

57 lines
1.8 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from "@/app/api/auth/options";
import { NotificationService } from '@/lib/services/notifications/notification-service';
// GET /api/notifications?page=1&limit=20
export async function GET(request: Request) {
try {
// Authenticate user
const session = await getServerSession(authOptions);
if (!session || !session.user?.id) {
return NextResponse.json(
{ error: "Not authenticated" },
{ status: 401 }
);
}
const userId = session.user.id;
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') || '1', 10);
const limit = parseInt(searchParams.get('limit') || '20', 10);
// Validate parameters
if (isNaN(page) || page < 1) {
return NextResponse.json(
{ error: "Invalid page parameter" },
{ status: 400 }
);
}
if (isNaN(limit) || limit < 1 || limit > 100) {
return NextResponse.json(
{ error: "Invalid limit parameter, must be between 1 and 100" },
{ status: 400 }
);
}
const notificationService = NotificationService.getInstance();
const notifications = await notificationService.getNotifications(userId, page, limit);
// Add Cache-Control header to help with client-side caching
const response = NextResponse.json({
notifications,
page,
limit,
total: notifications.length
});
response.headers.set('Cache-Control', 'private, max-age=30'); // Cache for 30 seconds on client
return response;
} catch (error: any) {
console.error('Error in notifications API:', error);
return NextResponse.json(
{ error: "Internal server error", message: error.message },
{ status: 500 }
);
}
}