(params: {
tools: Array<{
id?: string
title: string
schema: any
code: string
}>
workspaceId: string
userId: string
requestId?: string
})
| 12 | * Can be called from API routes or internal services |
| 13 | */ |
| 14 | export async function upsertCustomTools(params: { |
| 15 | tools: Array<{ |
| 16 | id?: string |
| 17 | title: string |
| 18 | schema: any |
| 19 | code: string |
| 20 | }> |
| 21 | workspaceId: string |
| 22 | userId: string |
| 23 | requestId?: string |
| 24 | }) { |
| 25 | const { tools, workspaceId, userId, requestId = generateRequestId() } = params |
| 26 | |
| 27 | return await db.transaction(async (tx) => { |
| 28 | for (const tool of tools) { |
| 29 | const nowTime = new Date() |
| 30 | |
| 31 | if (tool.id) { |
| 32 | const existingWorkspaceTool = await tx |
| 33 | .select() |
| 34 | .from(customTools) |
| 35 | .where(and(eq(customTools.id, tool.id), eq(customTools.workspaceId, workspaceId))) |
| 36 | .limit(1) |
| 37 | |
| 38 | if (existingWorkspaceTool.length > 0) { |
| 39 | await tx |
| 40 | .update(customTools) |
| 41 | .set({ |
| 42 | title: tool.title, |
| 43 | schema: tool.schema, |
| 44 | code: tool.code, |
| 45 | updatedAt: nowTime, |
| 46 | }) |
| 47 | .where(and(eq(customTools.id, tool.id), eq(customTools.workspaceId, workspaceId))) |
| 48 | continue |
| 49 | } |
| 50 | |
| 51 | const existingLegacyTool = await tx |
| 52 | .select() |
| 53 | .from(customTools) |
| 54 | .where( |
| 55 | and( |
| 56 | eq(customTools.id, tool.id), |
| 57 | isNull(customTools.workspaceId), |
| 58 | eq(customTools.userId, userId) |
| 59 | ) |
| 60 | ) |
| 61 | .limit(1) |
| 62 | |
| 63 | if (existingLegacyTool.length > 0) { |
| 64 | await tx |
| 65 | .update(customTools) |
| 66 | .set({ |
| 67 | title: tool.title, |
| 68 | schema: tool.schema, |
| 69 | code: tool.code, |
| 70 | updatedAt: nowTime, |
| 71 | }) |
no test coverage detected