This blog post provides a practical solution for grouping data by day, month, or year using Prisma. I struggled with this myself, so I'm sharing this streamlined approach. We'll use a Next.js API endpoint to analyze API call trends using Prisma and MongoDB, focusing on success rates and call frequency over time.
Effective dashboarding requires grouping API calls by time intervals. Let's use a concise Prisma schema:
<code>model ApiCall { id String @id @default(auto()) @map("_id") @db.ObjectId timestamp DateTime @default(now()) status ApiCallStatus // Enum for success or failure. } enum ApiCallStatus { SUCCESS FAILURE }</code>
This schema tracks each API call's timestamp and status, sufficient for trend analysis.
This Next.js API endpoint aggregates API call data, grouping it by specified time periods (year, month, or day):
<code>import { NextRequest, NextResponse } from 'next/server'; import { startOfYear, endOfYear, startOfMonth, endOfMonth } from 'date-fns'; export async function GET(req: NextRequest) { const range = req.nextUrl.searchParams.get("range"); // 'year' or 'month' const groupBy = req.nextUrl.searchParams.get("groupby"); // 'yearly', 'monthly', 'daily' // Input validation if (!range || (range !== 'year' && range !== 'month')) { return NextResponse.json({ error: "Range must be 'year' or 'month'" }, { status: 400 }); } if (!groupBy || (groupBy !== 'yearly' && groupBy !== 'monthly' && groupBy !== 'daily')) { return NextResponse.json({ error: "Group by must be 'yearly', 'monthly', or 'daily'" }, { status: 400 }); } try { let start: Date, end: Date; if (range === 'year') { start = startOfYear(new Date()); end = endOfYear(new Date()); } else { // range === 'month' start = startOfMonth(new Date()); end = endOfMonth(new Date()); } let groupByFormat: string; switch (groupBy) { case 'yearly': groupByFormat = "%Y"; break; case 'monthly': groupByFormat = "%Y-%m"; break; case 'daily': groupByFormat = "%Y-%m-%d"; break; } const apiCallTrends = await db.apiCall.aggregateRaw({ pipeline: [ { $match: { timestamp: { $gte: { $date: start }, $lte: { $date: end } } } }, { $group: { _id: { $dateToString: { format: groupByFormat, date: '$timestamp' } }, SUCCESS: { $sum: { $cond: [{ $eq: ['$status', 'SUCCESS'] }, 1, 0] } }, FAILURE: { $sum: { $cond: [{ $eq: ['$status', 'FAILURE'] }, 1, 0] } }, TOTAL: { $sum: 1 } } }, { $sort: { _id: 1 } } ] }); return NextResponse.json({ apiCallTrends }); } catch (error) { console.error(error); return NextResponse.json({ error: "An error occurred while fetching data." }, { status: 500 }); } }</code>
A request like this:
<code>GET /api/your-endpoint?range=year&groupby=monthly</code>
Might yield this response:
<code>{ "apiCallTrends": [ { "_id": "2025-01", // January 2025 "SUCCESS": 120, "FAILURE": 15, "TOTAL": 135 }, { "_id": "2025-02", // February 2025 "SUCCESS": 110, "FAILURE": 10, "TOTAL": 120 }, { "_id": "2025-03", // March 2025 "SUCCESS": 130, "FAILURE": 20, "TOTAL": 150 } // ... more monthly data ] }</code>
This approach provides a robust and efficient method for querying and analyzing timestamped data grouped by various time ranges within MongoDB, using the Prisma ORM. Thanks for reading! Please like and subscribe for more content! Connect with me on GitHub and LinkedIn.
The above is the detailed content of Analyzing API Call Trends with Prisma and Next.js: Grouping by Week, Month, or Year. For more information, please follow other related articles on the PHP Chinese website!