Skip to content

Commit 3778d33

Browse files
committed
Use helper for api key validation
1 parent fcf947d commit 3778d33

File tree

1 file changed

+8
-27
lines changed
  • apps/sim/app/api/copilot/api-keys/validate

1 file changed

+8
-27
lines changed

apps/sim/app/api/copilot/api-keys/validate/route.ts

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
import { db } from '@sim/db'
2-
import { userStats } from '@sim/db/schema'
3-
import { eq } from 'drizzle-orm'
41
import { type NextRequest, NextResponse } from 'next/server'
2+
import { checkServerSideUsageLimits } from '@/lib/billing/calculations/usage-monitor'
53
import { checkInternalApiKey } from '@/lib/copilot/utils'
64
import { createLogger } from '@/lib/logs/console/logger'
75

@@ -24,30 +22,13 @@ export async function POST(req: NextRequest) {
2422

2523
logger.info('[API VALIDATION] Validating usage limit', { userId })
2624

27-
const usage = await db
28-
.select({
29-
currentPeriodCost: userStats.currentPeriodCost,
30-
totalCost: userStats.totalCost,
31-
currentUsageLimit: userStats.currentUsageLimit,
32-
})
33-
.from(userStats)
34-
.where(eq(userStats.userId, userId))
35-
.limit(1)
36-
37-
logger.info('[API VALIDATION] Usage limit validated', { userId, usage })
38-
39-
if (usage.length > 0) {
40-
const currentUsage = Number.parseFloat(
41-
(usage[0].currentPeriodCost?.toString() as string) ||
42-
(usage[0].totalCost as unknown as string) ||
43-
'0'
44-
)
45-
const limit = Number.parseFloat((usage[0].currentUsageLimit as unknown as string) || '0')
46-
47-
if (!Number.isNaN(limit) && limit > 0 && currentUsage >= limit) {
48-
logger.info('[API VALIDATION] Usage exceeded', { userId, currentUsage, limit })
49-
return new NextResponse(null, { status: 402 })
50-
}
25+
const { isExceeded, currentUsage, limit } = await checkServerSideUsageLimits(userId)
26+
27+
logger.info('[API VALIDATION] Usage limit validated', { userId, currentUsage, limit, isExceeded })
28+
29+
if (isExceeded) {
30+
logger.info('[API VALIDATION] Usage exceeded', { userId, currentUsage, limit })
31+
return new NextResponse(null, { status: 402 })
5132
}
5233

5334
return new NextResponse(null, { status: 200 })

0 commit comments

Comments
 (0)