Skip to content

Commit b95ea91

Browse files
authored
fix(copilot): consolidate usage limit validation (#1763)
* Use helper for api key validation * Lint
1 parent fcf947d commit b95ea91

File tree

1 file changed

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

1 file changed

+13
-27
lines changed

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

Lines changed: 13 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,18 @@ 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', {
28+
userId,
29+
currentUsage,
30+
limit,
31+
isExceeded,
32+
})
33+
34+
if (isExceeded) {
35+
logger.info('[API VALIDATION] Usage exceeded', { userId, currentUsage, limit })
36+
return new NextResponse(null, { status: 402 })
5137
}
5238

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

0 commit comments

Comments
 (0)