-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathroute.ts
More file actions
153 lines (131 loc) · 5.28 KB
/
route.ts
File metadata and controls
153 lines (131 loc) · 5.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import { db } from '@sim/db'
import { workflow } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/auth'
import { generateRequestId } from '@/lib/core/utils/request'
import { getWorkflowAccessContext } from '@/lib/workflows/utils'
import type { Variable } from '@/stores/panel/variables/types'
const logger = createLogger('WorkflowVariablesAPI')
const VariableSchema = z.object({
id: z.string(),
workflowId: z.string(),
name: z.string(),
type: z.enum(['string', 'number', 'boolean', 'object', 'array', 'plain']),
value: z.union([
z.string(),
z.number(),
z.boolean(),
z.record(z.unknown()),
z.array(z.unknown()),
]),
})
const VariablesSchema = z.object({
variables: z.record(z.string(), VariableSchema),
})
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const requestId = generateRequestId()
const workflowId = (await params).id
try {
const session = await getSession()
if (!session?.user?.id) {
logger.warn(`[${requestId}] Unauthorized workflow variables update attempt`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Get the workflow record
const accessContext = await getWorkflowAccessContext(workflowId, session.user.id)
const workflowData = accessContext?.workflow
if (!workflowData) {
logger.warn(`[${requestId}] Workflow not found: ${workflowId}`)
return NextResponse.json({ error: 'Workflow not found' }, { status: 404 })
}
const workspaceId = workflowData.workspaceId
// Check authorization - either the user owns the workflow or has workspace permissions
const isAuthorized =
accessContext?.isOwner || (workspaceId ? accessContext?.workspacePermission !== null : false)
if (!isAuthorized) {
logger.warn(
`[${requestId}] User ${session.user.id} attempted to update variables for workflow ${workflowId} without permission`
)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const body = await req.json()
try {
const { variables } = VariablesSchema.parse(body)
// Variables are already in Record format - use directly
// The frontend is the source of truth for what variables should exist
await db
.update(workflow)
.set({
variables,
updatedAt: new Date(),
})
.where(eq(workflow.id, workflowId))
return NextResponse.json({ success: true })
} catch (validationError) {
if (validationError instanceof z.ZodError) {
logger.warn(`[${requestId}] Invalid workflow variables data`, {
errors: validationError.errors,
})
return NextResponse.json(
{ error: 'Invalid request data', details: validationError.errors },
{ status: 400 }
)
}
throw validationError
}
} catch (error) {
logger.error(`[${requestId}] Error updating workflow variables`, error)
return NextResponse.json({ error: 'Failed to update workflow variables' }, { status: 500 })
}
}
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const requestId = generateRequestId()
const workflowId = (await params).id
try {
// Get the session directly in the API route
const session = await getSession()
if (!session?.user?.id) {
logger.warn(`[${requestId}] Unauthorized workflow variables access attempt`)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Get the workflow record
const accessContext = await getWorkflowAccessContext(workflowId, session.user.id)
const workflowData = accessContext?.workflow
if (!workflowData) {
logger.warn(`[${requestId}] Workflow not found: ${workflowId}`)
return NextResponse.json({ error: 'Workflow not found' }, { status: 404 })
}
const workspaceId = workflowData.workspaceId
// Check authorization - either the user owns the workflow or has workspace permissions
const isAuthorized =
accessContext?.isOwner || (workspaceId ? accessContext?.workspacePermission !== null : false)
if (!isAuthorized) {
logger.warn(
`[${requestId}] User ${session.user.id} attempted to access variables for workflow ${workflowId} without permission`
)
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
// Return variables if they exist
const variables = (workflowData.variables as Record<string, Variable>) || {}
// Add cache headers to prevent frequent reloading
const variableHash = JSON.stringify(variables).length
const headers = new Headers({
'Cache-Control': 'max-age=30, stale-while-revalidate=300', // Cache for 30 seconds, stale for 5 min
ETag: `"variables-${workflowId}-${variableHash}"`,
})
return NextResponse.json(
{ data: variables },
{
status: 200,
headers,
}
)
} catch (error) {
logger.error(`[${requestId}] Workflow variables fetch error`, error)
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
return NextResponse.json({ error: errorMessage }, { status: 500 })
}
}