这篇博文提供了使用 Prisma 按日、月或年对数据进行分组的实用解决方案。 我自己也曾为此苦苦挣扎,所以我分享这种简化的方法。我们将使用 Next.js API 端点来分析使用 Prisma 和 MongoDB 的 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 调用的时间戳和状态,足以进行趋势分析。
此 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>
这种方法提供了一种强大而高效的方法,用于使用 Prisma ORM 查询和分析 MongoDB 中按不同时间范围分组的时间戳数据。 感谢您的阅读! 请点赞并订阅以获取更多内容! 在 GitHub 和 LinkedIn 上与我联系。
以上是使用 Prisma 和 Next.js 分析 API 调用趋势:按周、月或年分组的详细内容。更多信息请关注PHP中文网其他相关文章!