fixed possible race condition when paying with gems
This commit is contained in:
parent
4798b2a0c6
commit
676bd7a978
|
|
@ -18,17 +18,21 @@ export const addGems = async (
|
||||||
user: string,
|
user: string,
|
||||||
gems: number,
|
gems: number,
|
||||||
) => {
|
) => {
|
||||||
const { count, totalCount } = await getGems(db, user);
|
await db.transaction(async (tx) => {
|
||||||
if ((await db.select().from(Gems).where(eq(Gems.user, user))).length === 0) {
|
const res = (await tx.select().from(Gems).where(eq(Gems.user, user)))[0];
|
||||||
await db
|
const count = res?.count ?? 0;
|
||||||
.insert(Gems)
|
const totalCount = res?.totalCount ?? 0;
|
||||||
.values({ user, count: count + gems, totalCount: totalCount + gems });
|
if (!res) {
|
||||||
return;
|
await tx
|
||||||
}
|
.insert(Gems)
|
||||||
await db
|
.values({ user, count: count + gems, totalCount: totalCount + gems });
|
||||||
.update(Gems)
|
return;
|
||||||
.set({ count: count + gems, totalCount: totalCount + gems })
|
}
|
||||||
.where(eq(Gems.user, user));
|
await tx
|
||||||
|
.update(Gems)
|
||||||
|
.set({ count: count + gems, totalCount: totalCount + gems })
|
||||||
|
.where(eq(Gems.user, user));
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const removeGems = async (
|
export const removeGems = async (
|
||||||
|
|
@ -36,10 +40,14 @@ export const removeGems = async (
|
||||||
user: string,
|
user: string,
|
||||||
gems: number,
|
gems: number,
|
||||||
) => {
|
) => {
|
||||||
const { count, totalCount } = await getGems(db, user);
|
await db.transaction(async (tx) => {
|
||||||
if (count - gems < 0) throw new Error("Not enough gems");
|
const res = (await tx.select().from(Gems).where(eq(Gems.user, user)))[0];
|
||||||
await db
|
const count = res?.count ?? 0;
|
||||||
.update(Gems)
|
const totalCount = res?.totalCount ?? 0;
|
||||||
.set({ count: count - gems, totalCount: totalCount })
|
if (count - gems < 0) throw new Error("Not enough gems");
|
||||||
.where(eq(Gems.user, user));
|
await tx
|
||||||
|
.update(Gems)
|
||||||
|
.set({ count: count - gems, totalCount: totalCount })
|
||||||
|
.where(eq(Gems.user, user));
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue