api call optimized

This commit is contained in:
dimitar committed 2026-03-11 03:43:34 +01:00
1 parent 97436c6823
commit 612259f020
12 files changed
+727 -177

No files matched your search

@@ -44,13 +44,39 @@ interface DashboardStatistics {
// GET - Fetch dashboard statistics for authenticated user
export async function GET(request: NextRequest) {
try {
const { userId } = await auth();
// Log the request details for debugging
log.debug("Statistics endpoint called", {
url: request.url,
hasAuthHeader: !!request.headers.get("authorization"),
authHeaderPreview: request.headers.get("authorization")?.substring(0, 30),
});
if (!userId) {
const { userId: authenticatedUserId } = await auth();
log.debug("Auth result", {
authenticatedUserId,
isAuthenticated: !!authenticatedUserId,
});
if (!authenticatedUserId) {
log.error("Statistics GET - authentication failed", {
hasAuthHeader: !!request.headers.get("authorization"),
url: request.url,
});
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
log.debug("Fetching statistics for user", { userId });
// Get target user ID from query params, default to authenticated user
const { searchParams } = new URL(request.url);
const userId = searchParams.get("userId") || authenticatedUserId;
// Users can only access their own statistics unless they're staff
// (we could add role checking here if needed)
log.debug("Fetching statistics for user", {
authenticatedUserId,
targetUserId: userId,
});
// Get goal statistics
const goals = db
@@ -284,11 +310,39 @@ export async function GET(request: NextRequest) {
totalCheckIns,
});
return NextResponse.json({ statistics });
return NextResponse.json({
success: true,
data: {
statistics: {
userId,
...statistics,
},
},
meta: {
timestamp: new Date().toISOString(),
requestId: `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
},
});
return NextResponse.json({
success: true,
data: { statistics },
meta: {
timestamp: new Date().toISOString(),
requestId: `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
},
});
} catch (error) {
log.error("Failed to fetch statistics", error);
return NextResponse.json(
{ error: "Failed to fetch statistics" },
{
success: false,
error: { message: "Failed to fetch statistics" },
meta: {
timestamp: new Date().toISOString(),
requestId: `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
},
},
{ status: 500 },
);
}