首页 > web前端 > js教程 > 正文

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

花韻仙語
发布: 2025-01-20 08:04:21
原创
366人浏览过

使用 prisma 和 nextjs 分析 api 调用趋势:按周、月或年分组

本文将阐述如何利用 Prisma 根据日期(日、月或年)对数据进行分组,并结合 Next.js 和 MongoDB,构建一个 API 调用趋势分析工具。通过这个示例,我们将学习如何查询数据,追踪 API 调用指标,例如一段时间内的成功率和调用频率。

简化 API 调用数据模型

为了有效分析 API 调用趋势,特别是按周、月或年分组,我们需要一个精简的数据模型。以下 Prisma 架构足以满足需求:

model apicall {
  id        string    @id @default(auto()) @map("_id") @db.objectid
  timestamp datetime  @default(now())
  status    apicallstatus // success 或 failure 枚举
}

enum apicallstatus {
  success
  failure
}
登录后复制

该模型记录每个 API 调用的时间戳和状态,为趋势分析提供必要信息。

查询 API 调用趋势

以下代码展示了 Next.js API 端点的实现,该端点通过按不同时间段分组数据,提供 API 调用趋势的洞察。此端点有助于监控 API 使用模式,并有效识别潜在的系统问题:

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' 或 'month'
    const groupBy = req.nextUrl.searchParams.get("groupBy"); // 'yearly', 'monthly', 'daily'

    if (!range || (range !== 'year' && range !== 'month')) {
        return NextResponse.json({ error: "range 必须为 'year' 或 'month'" }, { status: 400 });
    }

    if (!groupBy || (groupBy !== 'yearly' && groupBy !== 'monthly' && groupBy !== 'daily')) {
        return NextResponse.json({ error: "groupBy 必须为 'yearly', 'monthly' 或 '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: "获取数据时发生错误。" }, { status: 500 });
    }
}
登录后复制

可能的响应

例如,请求 /api/your-endpoint?range=year&groupBy=monthly 可能返回以下 JSON 数据:

{
  "apiCallTrends": [
    {
      "_id": "2025-01", // 按月份分组 (2025年1月)
      "success": 120,
      "failure": 15,
      "total": 135
    },
    {
      "_id": "2025-02", // 按月份分组 (2025年2月)
      "success": 110,
      "failure": 10,
      "total": 120
    },
    {
      "_id": "2025-03", // 按月份分组 (2025年3月)
      "success": 130,
      "failure": 20,
      "total": 150
    }
    // ...更多按月分组的结果
  ]
}
登录后复制

主要亮点

  • 动态日期分组: 根据用户请求参数,灵活地按年、月或日对 API 调用进行分组。
  • 趋势分析: 计算每个时间段的成功、失败次数以及总调用次数。
  • 错误处理: 提供友好的错误信息,提升 API 使用体验。
  • 效率: 利用 MongoDB 的聚合管道,优化查询性能,减少服务器负载。

结论

本方案展示了如何使用 Prisma ORM 从 MongoDB 中查询并按不同时间范围对时间戳进行分组。 希望本文对您有所帮助!

以上就是使用 Prisma 和 Nextjs 分析 API 调用趋势:按周、月或年分组的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号