Selaa lähdekoodia

2小时后自动结束

charles_c 5 kuukautta sitten
vanhempi
commit
780eeee295
1 muutettua tiedostoa jossa 45 lisäystä ja 14 poistoa
  1. 45 14
      src/app/api/match/route.js

+ 45 - 14
src/app/api/match/route.js

@@ -26,6 +26,11 @@ export async function GET(request) {
     const currentDate = now.toDate();
     const currentTimeString = now.format("HH:mm");
 
+    // 创建2小时前的时间点
+    const twoHoursAgo = moment(now).subtract(2, "hours");
+    const twoHoursAgoDate = twoHoursAgo.format("YYYY-MM-DD"); // 使用日期字符串
+    const twoHoursAgoTime = twoHoursAgo.format("HH:mm");
+
     switch (action) {
       case "getMatches":
         const searchQuery = {};
@@ -81,16 +86,44 @@ export async function GET(request) {
 
         console.log("Search Query:", searchQuery);
 
-        // 更新比赛状态(考虑比赛类型)
-        await Match.updateMany(
-          {
-            date: { $lte: currentDate },
-            time: { $lte: currentTimeString },
-            status: "未开始",
-            ...(type ? { type } : {}),
-          },
-          { $set: { status: "进行中" } }
-        );
+        await Promise.all([
+          // 更新所有开始超过2小时的比赛为已结束
+          Match.updateMany(
+            {
+              $or: [
+                // 早于今天的比赛
+                { date: { $lt: twoHoursAgoDate } },
+                // 今天的比赛且开始时间在2小时前
+                {
+                  date: twoHoursAgoDate,
+                  time: { $lte: twoHoursAgoTime },
+                },
+              ],
+              status: { $in: ["未开始", "进行中"] },
+              ...(type ? { type } : {}),
+            },
+            { $set: { status: "已结束" } }
+          ),
+
+          // 更新其他应该进行中的比赛
+          Match.updateMany(
+            {
+              date: { $lte: currentDate },
+              time: { $lte: currentTimeString },
+              status: "未开始",
+              // 排除已经过去2小时的比赛(因为上面的查询会处理)
+              $or: [
+                { date: { $gt: twoHoursAgoDate } },
+                {
+                  date: twoHoursAgoDate,
+                  time: { $gt: twoHoursAgoTime },
+                },
+              ],
+              ...(type ? { type } : {}),
+            },
+            { $set: { status: "进行中" } }
+          ),
+        ]);
 
         const skip = (current - 1) * pageSize;
         const totalMatches = await Match.countDocuments(searchQuery);
@@ -108,12 +141,10 @@ export async function GET(request) {
 
       case "getMatchDays":
         const typeFilter = type ? { type } : {};
-        const currentDate = moment().tz(timezone).startOf("day");
-
-        console.log(111, typeFilter);
+        const currentDay = moment().tz(timezone).startOf("day");
 
         const futureMatches = await Match.find({
-          date: { $gte: currentDate.toDate() },
+          date: { $gte: currentDay.toDate() },
           status: { $in: ["未开始", "进行中"] },
           ...typeFilter,
         }).sort("date");