Table of Contents
Simplified API Call Data Structure
Querying API Call Trends: A Next.js API Endpoint
Sample Response
Key Features
Conclusion
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

Jan 20, 2025 am 02:33 AM

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.

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

jQuery Check if Date is Valid

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

jQuery get element padding/margin

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

10 jQuery Accordions Tabs

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

10 Worth Checking Out jQuery Plugins

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

HTTP Debugging with Node and http-console

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

jquery add scrollbar to div

See all articles