Skip to content

Commit ad10971

Browse files
committed
move userstats record creation inside tx
1 parent 7201374 commit ad10971

File tree

2 files changed

+26
-26
lines changed

2 files changed

+26
-26
lines changed

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

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -142,19 +142,6 @@ export async function POST() {
142142
return NextResponse.json({ attributed: false, reason: 'account_predates_cookie' })
143143
}
144144

145-
const [existingStats] = await db
146-
.select({ id: userStats.id })
147-
.from(userStats)
148-
.where(eq(userStats.userId, session.user.id))
149-
.limit(1)
150-
151-
if (!existingStats) {
152-
await db.insert(userStats).values({
153-
id: nanoid(),
154-
userId: session.user.id,
155-
})
156-
}
157-
158145
const matchedCampaign = await findMatchingCampaign(utmData)
159146
if (!matchedCampaign) {
160147
cookieStore.delete(COOKIE_NAME)
@@ -165,6 +152,19 @@ export async function POST() {
165152

166153
let attributed = false
167154
await db.transaction(async (tx) => {
155+
const [existingStats] = await tx
156+
.select({ id: userStats.id })
157+
.from(userStats)
158+
.where(eq(userStats.userId, session.user.id))
159+
.limit(1)
160+
161+
if (!existingStats) {
162+
await tx.insert(userStats).values({
163+
id: nanoid(),
164+
userId: session.user.id,
165+
})
166+
}
167+
168168
const result = await tx
169169
.insert(referralAttribution)
170170
.values({

apps/sim/app/api/referral-code/redeem/route.ts

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -97,23 +97,23 @@ export async function POST(request: Request) {
9797
}
9898
}
9999

100-
const [existingStats] = await db
101-
.select({ id: userStats.id })
102-
.from(userStats)
103-
.where(eq(userStats.userId, session.user.id))
104-
.limit(1)
105-
106-
if (!existingStats) {
107-
await db.insert(userStats).values({
108-
id: nanoid(),
109-
userId: session.user.id,
110-
})
111-
}
112-
113100
const bonusAmount = Number(campaign.bonusCreditAmount)
114101

115102
let redeemed = false
116103
await db.transaction(async (tx) => {
104+
const [existingStats] = await tx
105+
.select({ id: userStats.id })
106+
.from(userStats)
107+
.where(eq(userStats.userId, session.user.id))
108+
.limit(1)
109+
110+
if (!existingStats) {
111+
await tx.insert(userStats).values({
112+
id: nanoid(),
113+
userId: session.user.id,
114+
})
115+
}
116+
117117
const result = await tx
118118
.insert(referralAttribution)
119119
.values({

0 commit comments

Comments
 (0)