


Analyzing API Call Trends with Prisma and Next.js: Grouping by Week, Month, or Year
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.
Simplified API Call Data Structure
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.
Querying API Call Trends: A Next.js API Endpoint
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>
Sample Response
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>
Key Features
- Flexible Time Grouping: Easily group by year, month, or day.
- Comprehensive Trend Analysis: Provides success/failure counts and totals for each period.
- Robust Error Handling: Includes clear error responses.
- Optimized Performance: Leverages MongoDB's aggregation pipeline for efficiency.
Conclusion
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Replace String Characters in JavaScript

HTTP Debugging with Node and http-console

Custom Google Search API Setup Tutorial
