refactor: use prisma nested create instead

This commit is contained in:
Methapon Metanipat 2024-08-19 10:55:32 +07:00
parent 17e00ae60f
commit ab484f4026
2 changed files with 138 additions and 192 deletions

View file

@ -286,34 +286,12 @@ export class ServiceController extends Controller {
update: { value: { increment: 1 } },
});
const workList = await Promise.all(
(work || []).map(async (w, wIdx) =>
tx.work.create({
data: {
name: w.name,
order: wIdx + 1,
attributes: w.attributes,
productOnWork: {
createMany: {
data: w.productId.map((p, pIdx) => ({
productId: p,
order: pIdx + 1,
})),
},
},
},
}),
),
);
return tx.service.create({
include: {
work: {
include: {
productOnWork: {
include: {
product: true,
},
include: { product: true },
orderBy: { order: "asc" },
},
},
@ -326,7 +304,19 @@ export class ServiceController extends Controller {
productTypeId,
statusOrder: +(body.status === "INACTIVE"),
code: `${body.code.toLocaleUpperCase()}${last.value.toString().padStart(3, "0")}`,
work: { connect: workList.map((v) => ({ id: v.id })) },
work: {
create: (work || []).map((w, wIdx) => ({
name: w.name,
order: wIdx + 1,
attributes: w.attributes,
productOnWork: {
create: w.productId.map((p, pIdx) => ({
productId: p,
order: pIdx + 1,
})),
},
})),
},
createdByUserId: req.user.sub,
updatedByUserId: req.user.sub,
},
@ -412,26 +402,6 @@ export class ServiceController extends Controller {
}
const record = await prisma.$transaction(async (tx) => {
const workList = await Promise.all(
(work || []).map(async (w, wIdx) =>
tx.work.create({
data: {
name: w.name,
order: wIdx + 1,
attributes: w.attributes,
productOnWork: {
createMany: {
data: w.productId.map((p, pIdx) => ({
productId: p,
order: pIdx + 1,
})),
},
},
},
}),
),
);
return await tx.service.update({
include: {
createdBy: true,
@ -442,7 +412,17 @@ export class ServiceController extends Controller {
statusOrder: +(payload.status === "INACTIVE"),
work: {
deleteMany: {},
connect: workList.map((v) => ({ id: v.id })),
create: (work || []).map((w, wIdx) => ({
name: w.name,
order: wIdx + 1,
attributes: w.attributes,
productOnWork: {
create: w.productId.map((p, pIdx) => ({
productId: p,
order: pIdx + 1,
})),
},
})),
},
updatedByUserId: req.user.sub,
},