(params: {
workspaceId: string
envKeys: string[]
actingUserId: string
})
| 175 | } |
| 176 | |
| 177 | export async function syncWorkspaceEnvCredentials(params: { |
| 178 | workspaceId: string |
| 179 | envKeys: string[] |
| 180 | actingUserId: string |
| 181 | }) { |
| 182 | const { workspaceId, envKeys, actingUserId } = params |
| 183 | const { ownerId, memberUserIds } = await getWorkspaceMembership(workspaceId) |
| 184 | |
| 185 | if (!ownerId) return |
| 186 | |
| 187 | const normalizedKeys = Array.from(new Set(envKeys.filter(Boolean))) |
| 188 | const existingCredentials = await db |
| 189 | .select({ |
| 190 | id: credential.id, |
| 191 | envKey: credential.envKey, |
| 192 | }) |
| 193 | .from(credential) |
| 194 | .where(and(eq(credential.workspaceId, workspaceId), eq(credential.type, 'env_workspace'))) |
| 195 | |
| 196 | const existingByKey = new Map( |
| 197 | existingCredentials |
| 198 | .filter((row): row is { id: string; envKey: string } => Boolean(row.envKey)) |
| 199 | .map((row) => [row.envKey, row.id]) |
| 200 | ) |
| 201 | |
| 202 | const credentialIdsToEnsureMembership = new Set<string>() |
| 203 | const now = new Date() |
| 204 | |
| 205 | for (const envKey of normalizedKeys) { |
| 206 | const existingId = existingByKey.get(envKey) |
| 207 | if (existingId) credentialIdsToEnsureMembership.add(existingId) |
| 208 | } |
| 209 | |
| 210 | const keysToCreate = normalizedKeys.filter((key) => !existingByKey.has(key)) |
| 211 | if (keysToCreate.length > 0) { |
| 212 | const inserted = await db |
| 213 | .insert(credential) |
| 214 | .values( |
| 215 | keysToCreate.map((envKey) => ({ |
| 216 | id: generateId(), |
| 217 | workspaceId, |
| 218 | type: 'env_workspace' as const, |
| 219 | displayName: envKey, |
| 220 | envKey, |
| 221 | createdBy: actingUserId, |
| 222 | createdAt: now, |
| 223 | updatedAt: now, |
| 224 | })) |
| 225 | ) |
| 226 | .onConflictDoNothing() |
| 227 | .returning({ id: credential.id }) |
| 228 | for (const row of inserted) { |
| 229 | credentialIdsToEnsureMembership.add(row.id) |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | for (const credentialId of credentialIdsToEnsureMembership) { |
| 234 | await ensureWorkspaceCredentialMemberships(credentialId, memberUserIds, ownerId) |
no test coverage detected