首页 >web前端 >js教程 >使用 Prisma 和 Next.js 分析 API 调用趋势:按周、月或年分组

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

Susan Sarandon
Susan Sarandon原创
2025-01-20 02:33:10903浏览

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