feat: use retry function

This commit is contained in:
Methapon Metanipat 2024-10-22 17:59:31 +07:00
parent 6235186ff9
commit dfd927eeb4

View file

@ -46,6 +46,7 @@ import {
} from "../services/permission"; } from "../services/permission";
import { connectOrDisconnect, connectOrNot, whereAddressQuery } from "../utils/relation"; import { connectOrDisconnect, connectOrNot, whereAddressQuery } from "../utils/relation";
import { isUsedError, notFoundError, relationError } from "../utils/error"; import { isUsedError, notFoundError, relationError } from "../utils/error";
import { retry } from "../utils/func";
if (!process.env.MINIO_BUCKET) { if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket."); throw Error("Require MinIO bucket.");
@ -174,36 +175,38 @@ const permissionCond = createPermCondition(globalAllow);
const permissionCheck = createPermCheck(globalAllow); const permissionCheck = createPermCheck(globalAllow);
async function userBranchCodeGen(user: User, branch: Branch) { async function userBranchCodeGen(user: User, branch: Branch) {
return await prisma.$transaction( return await retry(() =>
async (tx) => { prisma.$transaction(
const typ = user.userType; async (tx) => {
const typ = user.userType;
const mapTypeNo = { const mapTypeNo = {
USER: 1, USER: 1,
MESSENGER: 2, MESSENGER: 2,
DELEGATE: 3, DELEGATE: 3,
AGENCY: 4, AGENCY: 4,
}[typ]; }[typ];
const last = await tx.runningNo.upsert({ const last = await tx.runningNo.upsert({
where: { where: {
key: `BR_USR_${branch.code}_${mapTypeNo}`, key: `BR_USR_${branch.code}_${mapTypeNo}`,
}, },
create: { create: {
key: `BR_USR_${branch.code}_${mapTypeNo}`, key: `BR_USR_${branch.code}_${mapTypeNo}`,
value: 1, value: 1,
}, },
update: { value: { increment: 1 } }, update: { value: { increment: 1 } },
}); });
return await tx.user.update({ return await tx.user.update({
where: { id: user.id }, where: { id: user.id },
data: { data: {
code: mapTypeNo + `${last.value}`.padStart(6, "0"), code: mapTypeNo + `${last.value}`.padStart(6, "0"),
}, },
}); });
}, },
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable }, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
),
); );
} }