Skip to content

Commit 4f5500f

Browse files
committed
fix tx issue
1 parent 34ca49a commit 4f5500f

1 file changed

Lines changed: 31 additions & 23 deletions

File tree

  • apps/sim/app/api/credentials/memberships

apps/sim/app/api/credentials/memberships/route.ts

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -76,33 +76,41 @@ export async function DELETE(request: NextRequest) {
7676
return NextResponse.json({ success: true }, { status: 200 })
7777
}
7878

79-
if (membership.role === 'admin') {
80-
const activeAdmins = await db
81-
.select({ id: credentialMember.id })
82-
.from(credentialMember)
83-
.where(
84-
and(
85-
eq(credentialMember.credentialId, credentialId),
86-
eq(credentialMember.role, 'admin'),
87-
eq(credentialMember.status, 'active')
79+
const revoked = await db.transaction(async (tx) => {
80+
if (membership.role === 'admin') {
81+
const activeAdmins = await tx
82+
.select({ id: credentialMember.id })
83+
.from(credentialMember)
84+
.where(
85+
and(
86+
eq(credentialMember.credentialId, credentialId),
87+
eq(credentialMember.role, 'admin'),
88+
eq(credentialMember.status, 'active')
89+
)
8890
)
89-
)
9091

91-
if (activeAdmins.length <= 1) {
92-
return NextResponse.json(
93-
{ error: 'Cannot leave credential as the last active admin' },
94-
{ status: 400 }
95-
)
92+
if (activeAdmins.length <= 1) {
93+
return false
94+
}
9695
}
97-
}
9896

99-
await db
100-
.update(credentialMember)
101-
.set({
102-
status: 'revoked',
103-
updatedAt: new Date(),
104-
})
105-
.where(eq(credentialMember.id, membership.id))
97+
await tx
98+
.update(credentialMember)
99+
.set({
100+
status: 'revoked',
101+
updatedAt: new Date(),
102+
})
103+
.where(eq(credentialMember.id, membership.id))
104+
105+
return true
106+
})
107+
108+
if (!revoked) {
109+
return NextResponse.json(
110+
{ error: 'Cannot leave credential as the last active admin' },
111+
{ status: 400 }
112+
)
113+
}
106114

107115
return NextResponse.json({ success: true }, { status: 200 })
108116
} catch (error) {

0 commit comments

Comments
 (0)