Home > Web Front-end > JS Tutorial > Analyzing API Call Trends with Prisma and Next.js: Grouping by Week, Month, or Year

Analyzing API Call Trends with Prisma and Next.js: Grouping by Week, Month, or Year

Susan Sarandon
Release: 2025-01-20 02:33:10
Original
866 people have browsed it

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>
Copy after login

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>
Copy after login

Sample Response

A request like this:

<code>GET /api/your-endpoint?range=year&groupby=monthly</code>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template