Files
altbin.dev/lib/stats.ts
T

52 lines
1.5 KiB
TypeScript
Raw Normal View History

2025-08-20 17:14:23 +02:00
import { prisma } from "@/lib/prisma";
2025-08-20 14:14:33 +02:00
export async function getDashboardStats(userId?: string) {
2025-08-20 17:14:23 +02:00
const where = userId ? { createdBy: userId } : undefined;
2025-08-20 14:14:33 +02:00
2025-08-20 17:14:23 +02:00
const [totalPastes, totalViews, recentPastes, apiUsage, storageUsed, avgViews, mostViewed, avgSize] =
await Promise.all([
prisma.paste.count({ where }),
prisma.paste.aggregate({ _sum: { views: true }, where }),
prisma.paste.count({
where: {
createdAt: { gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) },
...(userId ? { createdBy: userId } : {}),
},
}),
prisma.paste.count({ where: { createdBy: { not: null } } }),
prisma.paste.aggregate({ _sum: { size: true }, where }),
prisma.paste.aggregate({ _avg: { views: true }, where }),
prisma.paste.findFirst({
orderBy: { views: "desc" },
select: { views: true },
where,
}),
prisma.paste.aggregate({ _avg: { size: true }, where }),
]);
2025-08-20 14:14:33 +02:00
return {
totalPastes,
totalViews: totalViews._sum.views || 0,
recentPastes,
apiUsage,
storageUsed: storageUsed._sum.size || 0,
avgViews: Number(avgViews._avg.views?.toFixed(1)) || 0,
mostViewed: mostViewed?.views || 0,
avgSize: avgSize._avg.size || 0,
};
}
export async function getUserPastes(userId: string) {
2025-08-20 17:14:23 +02:00
return prisma.paste.findMany({
2025-08-20 14:14:33 +02:00
where: { createdBy: userId },
2025-08-20 17:14:23 +02:00
orderBy: { createdAt: "desc" },
2025-08-20 14:14:33 +02:00
select: {
id: true,
createdAt: true,
views: true,
title: true,
content: true,
},
});
2025-08-20 17:14:23 +02:00
}