-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathroute.ts
More file actions
69 lines (63 loc) · 1.91 KB
/
route.ts
File metadata and controls
69 lines (63 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { withAdminAuth } from "@/lib/server-auth";
import { logger } from "@/lib/logger";
import { parseQuery } from "@/lib/validation";
import { analyticsQuerySchema } from "@/lib/validation/schemas/admin";
export const GET = withAdminAuth(
async (request: NextRequest, _context, _user) => {
try {
const { searchParams } = new URL(request.url);
const parsed = parseQuery(searchParams, analyticsQuerySchema);
if (!parsed.success) return parsed.response;
const filterIp = parsed.data.ip ?? null;
const totalVisits = await prisma.visitorLog.count();
const uniqueIps = await prisma.visitorLog.groupBy({
by: ["ip"],
});
let filteredVisits: unknown[] = [];
if (filterIp) {
filteredVisits = await prisma.visitorLog.findMany({
where: {
ip: {
contains: filterIp,
},
},
orderBy: { createdAt: "desc" },
take: 100,
});
} else {
filteredVisits = await prisma.visitorLog.findMany({
orderBy: { createdAt: "desc" },
take: 100,
});
}
const topIps = await prisma.visitorLog.groupBy({
by: ["ip"],
_count: { ip: true },
orderBy: { _count: { ip: "desc" } },
take: 10,
});
return NextResponse.json({
stats: {
totalVisits,
uniqueVisitors: uniqueIps.length,
},
topIps: topIps.map((item) => ({
ip: item.ip,
count: item._count.ip,
})),
visits: filteredVisits,
});
} catch (error) {
logger.error(
{ err: error, route: "/api/admin/analytics" },
"Error fetching analytics"
);
return NextResponse.json(
{ error: "Failed to fetch analytics" },
{ status: 500 }
);
}
}
);