Skip to content

Commit cb99aa7

Browse files
committed
fix: add pagination to GET /api/workflows (#3435)
1 parent 4c12914 commit cb99aa7

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

apps/sim/app/api/workflows/route.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { db } from '@sim/db'
22
import { permissions, workflow, workflowFolder } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
4-
import { and, asc, eq, inArray, isNull, min } from 'drizzle-orm'
4+
import { and, asc, eq, gt, inArray, isNull, min } from 'drizzle-orm'
55
import { type NextRequest, NextResponse } from 'next/server'
66
import { z } from 'zod'
77
import { AuditAction, AuditResourceType, recordAudit } from '@/lib/audit/log'
@@ -27,6 +27,9 @@ export async function GET(request: NextRequest) {
2727
const startTime = Date.now()
2828
const url = new URL(request.url)
2929
const workspaceId = url.searchParams.get('workspaceId')
30+
const cursor = url.searchParams.get('cursor')
31+
const limitParam = url.searchParams.get('limit')
32+
const limit = Math.min(Math.max(parseInt(limitParam || '100', 10) || 100, 1), 500)
3033

3134
try {
3235
const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false })
@@ -66,12 +69,16 @@ export async function GET(request: NextRequest) {
6669

6770
const orderByClause = [asc(workflow.sortOrder), asc(workflow.createdAt), asc(workflow.id)]
6871

72+
// Fetch limit+1 to detect if there are more pages
73+
const fetchLimit = limit + 1
74+
6975
if (workspaceId) {
7076
workflows = await db
7177
.select()
7278
.from(workflow)
7379
.where(eq(workflow.workspaceId, workspaceId))
7480
.orderBy(...orderByClause)
81+
.limit(fetchLimit)
7582
} else {
7683
const workspacePermissionRows = await db
7784
.select({ workspaceId: permissions.entityId })
@@ -86,9 +93,15 @@ export async function GET(request: NextRequest) {
8693
.from(workflow)
8794
.where(inArray(workflow.workspaceId, workspaceIds))
8895
.orderBy(...orderByClause)
96+
.limit(fetchLimit)
8997
}
9098

91-
return NextResponse.json({ data: workflows }, { status: 200 })
99+
// Determine if there are more results and set cursor
100+
const hasMore = workflows.length > limit
101+
const data = hasMore ? workflows.slice(0, limit) : workflows
102+
const nextCursor = hasMore ? data[data.length - 1]?.id : null
103+
104+
return NextResponse.json({ data, nextCursor }, { status: 200 })
92105
} catch (error: any) {
93106
const elapsed = Date.now() - startTime
94107
logger.error(`[${requestId}] Workflow fetch error after ${elapsed}ms`, error)

0 commit comments

Comments
 (0)