protofolio / backend /src /modules /analytics /analytics.service.ts
moustafa7
Initial commit
81d1e4c
Raw History Blame Contribute Delete
2.03 kB
import prisma from "../../config/database";
export class AnalyticsService {
async track(page: string, visitorIp?: string, userAgent?: string, referer?: string) {
return await prisma.analytics.create({
data: { page, visitorIp, userAgent, referer },
});
}
async getDashboard() {
const today = new Date();
today.setHours(0, 0, 0, 0);
const thisMonth = new Date(today.getFullYear(), today.getMonth(), 1);
try {
const [visitorsToday, monthlyVisitors, totalPageViews, recentViews, topProjects] =
await Promise.all([
prisma.analytics.groupBy({
by: ["visitorIp"],
where: { createdAt: { gte: today } },
}),
prisma.analytics.groupBy({
by: ["visitorIp"],
where: { createdAt: { gte: thisMonth } },
}),
prisma.analytics.count(),
prisma.analytics.findMany({
orderBy: { createdAt: "desc" },
take: 100,
}),
prisma.analytics.groupBy({
by: ["page"],
_count: { id: true },
where: { page: { startsWith: "/projects" } },
orderBy: { _count: { id: "desc" } },
take: 5,
}),
]);
let dailyVisitors: any[] = [];
try {
dailyVisitors = await prisma.$queryRaw`
SELECT DATE("createdAt") as date, COUNT(DISTINCT "visitorIp") as count
FROM "Analytics"
WHERE "createdAt" >= ${thisMonth}
GROUP BY DATE("createdAt")
ORDER BY date DESC
`;
} catch {
dailyVisitors = [];
}
return {
visitorsToday: visitorsToday.length,
monthlyVisitors: monthlyVisitors.length,
totalPageViews,
dailyVisitors,
topProjects,
recentViews,
};
} catch {
return {
visitorsToday: 0,
monthlyVisitors: 0,
totalPageViews: 0,
dailyVisitors: [],
topProjects: [],
recentViews: [],
};
}
}
}