目录
简化的API调用数据结构
查询 API 调用趋势:Next.js API 端点
示例响应
主要特点
结论
首页 web前端 js教程 使用 Prisma 和 Next.js 分析 API 调用趋势:按周、月或年分组

使用 Prisma 和 Next.js 分析 API 调用趋势:按周、月或年分组

Jan 20, 2025 am 02:33 AM

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

这篇博文提供了使用 Prisma 按日、月或年对数据进行分组的实用解决方案。 我自己也曾为此苦苦挣扎,所以我分享这种简化的方法。我们将使用 Next.js API 端点来分析使用 Prisma 和 MongoDB 的 API 调用趋势,重点关注一段时间内的成功率和调用频率。

简化的API调用数据结构

有效的仪表板需要按时间间隔对 API 调用进行分组。 让我们使用简洁的 Prisma 模式:

<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>
登录后复制

此模式跟踪每个 API 调用的时间戳和状态,足以进行趋势分析。

查询 API 调用趋势:Next.js API 端点

此 Next.js API 端点聚合 API 调用数据,并按指定时间段(年、月或日)对其进行分组:

<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>
登录后复制

示例响应

这样的请求:

<code>GET /api/your-endpoint?range=year&groupby=monthly</code>
登录后复制

可能会产生以下响应:

<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>
登录后复制

主要特点

  • 灵活的时间分组:轻松按年、月或日分组。
  • 综合趋势分析:提供每个时期的成功/失败计数和总计。
  • 强大的错误处理:包括清晰的错误响应。
  • 优化性能:利用 MongoDB 的聚合管道提高效率。

结论

这种方法提供了一种强大而高效的方法,用于使用 Prisma ORM 查询和分析 MongoDB 中按不同时间范围分组的时间戳数据。 感谢您的阅读! 请点赞并订阅以获取更多内容! 在 GitHub 和 LinkedIn 上与我联系。

以上是使用 Prisma 和 Next.js 分析 API 调用趋势:按周、月或年分组的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

在JavaScript中替换字符串字符 在JavaScript中替换字符串字符 Mar 11, 2025 am 12:07 AM

在JavaScript中替换字符串字符

jQuery检查日期是否有效 jQuery检查日期是否有效 Mar 01, 2025 am 08:51 AM

jQuery检查日期是否有效

jQuery获取元素填充/保证金 jQuery获取元素填充/保证金 Mar 01, 2025 am 08:53 AM

jQuery获取元素填充/保证金

10个jQuery手风琴选项卡 10个jQuery手风琴选项卡 Mar 01, 2025 am 01:34 AM

10个jQuery手风琴选项卡

10值得检查jQuery插件 10值得检查jQuery插件 Mar 01, 2025 am 01:29 AM

10值得检查jQuery插件

HTTP与节点和HTTP-Console调试 HTTP与节点和HTTP-Console调试 Mar 01, 2025 am 01:37 AM

HTTP与节点和HTTP-Console调试

自定义Google搜索API设置教程 自定义Google搜索API设置教程 Mar 04, 2025 am 01:06 AM

自定义Google搜索API设置教程

jQuery添加卷轴到Div jQuery添加卷轴到Div Mar 01, 2025 am 01:30 AM

jQuery添加卷轴到Div

See all articles