From 346d15460447a47cf7b5fc6d728579037997d438 Mon Sep 17 00:00:00 2001 From: javayhu Date: Sun, 10 Aug 2025 11:13:21 +0800 Subject: [PATCH] feat: support cron jobs --- src/app/api/distribute-credits/route.ts | 18 ++++++++++++++++++ src/credits/credits.ts | 8 ++++---- 2 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 src/app/api/distribute-credits/route.ts diff --git a/src/app/api/distribute-credits/route.ts b/src/app/api/distribute-credits/route.ts new file mode 100644 index 0000000..d8e55f4 --- /dev/null +++ b/src/app/api/distribute-credits/route.ts @@ -0,0 +1,18 @@ +import { distributeCreditsToAllUsers } from '@/credits/credits'; +import { NextResponse } from 'next/server'; + +/** + * distribute credits to all users daily + */ +export async function GET() { + console.log('distribute credits start'); + const { processedCount, errorCount } = await distributeCreditsToAllUsers(); + console.log( + `distribute credits end, processed: ${processedCount}, errors: ${errorCount}` + ); + return NextResponse.json({ + message: `distribute credits success, processed: ${processedCount}, errors: ${errorCount}`, + processedCount, + errorCount, + }); +} diff --git a/src/credits/credits.ts b/src/credits/credits.ts index 8edd58f..d2f3055 100644 --- a/src/credits/credits.ts +++ b/src/credits/credits.ts @@ -559,7 +559,7 @@ export async function addLifetimeMonthlyCredits(userId: string) { * This function is designed to be called by a cron job */ export async function distributeCreditsToAllUsers() { - console.log('distributing credits to all users start'); + console.log('distribute credits start'); const db = await getDb(); @@ -572,7 +572,7 @@ export async function distributeCreditsToAllUsers() { }) .from(user) .where(eq(user.banned, false)); // Only active users - console.log('distributing credits to all users, users count:', users.length); + console.log('distribute credits, users count:', users.length); let processedCount = 0; let errorCount = 0; @@ -609,7 +609,7 @@ export async function distributeCreditsToAllUsers() { processedCount++; } catch (error) { console.error( - `distributing credits to all users error, user: ${userRecord.userId}, error:`, + `distribute credits error, user: ${userRecord.userId}, error:`, error ); errorCount++; @@ -617,7 +617,7 @@ export async function distributeCreditsToAllUsers() { } console.log( - `distributing credits to all users end, processed: ${processedCount}, errors: ${errorCount}` + `distribute credits end, processed: ${processedCount}, errors: ${errorCount}` ); return { processedCount, errorCount }; }