refactor: use kysely query builder instead

This commit is contained in:
Methapon Metanipat 2024-09-03 09:24:10 +07:00
parent 7fa99fab8f
commit dfb2ab3928

View file

@ -14,8 +14,11 @@ export class ProductServiceController extends Controller {
@Query() pageSize: number = 30, @Query() pageSize: number = 30,
@Query() registeredBranchId?: string, @Query() registeredBranchId?: string,
) { ) {
const union = Prisma.sql` const union = prisma.$kysely
SELECT .selectFrom((eb) =>
eb
.selectFrom("Product")
.select([
"id", "id",
"code", "code",
"name", "name",
@ -33,19 +36,21 @@ export class ProductServiceController extends Controller {
"createdAt", "createdAt",
"updatedByUserId", "updatedByUserId",
"updatedAt", "updatedAt",
'product' as "type" sql<string>`'product'`.as("type"),
FROM "Product" ])
UNION ALL .union((eb) =>
SELECT eb
.selectFrom("Service")
.select([
"id", "id",
"code", "code",
"name", "name",
"detail", "detail",
null as "price", sql<number>`-1`.as("price"),
null as "agentPrice", sql<number>`-1`.as("agentPrice"),
null as "serviceCharge", sql<number>`-1`.as("serviceCharge"),
null as "process", sql<number>`-1`.as("process"),
null as "remark", sql<string>`'-'`.as("remark"),
"status", "status",
"statusOrder", "statusOrder",
"productTypeId", "productTypeId",
@ -54,56 +59,48 @@ export class ProductServiceController extends Controller {
"createdAt", "createdAt",
"updatedByUserId", "updatedByUserId",
"updatedAt", "updatedAt",
'service' as "type" sql<string>`'service'`.as("type"),
FROM "Service" ]),
`; )
.as("p"),
)
.where((eb) => {
const condStatus = status ? eb("status", "=", status) : undefined;
const condQuery = query ? eb("name", "like", `%${query}%`) : undefined;
const condProductTypeId = productTypeId
? eb("productTypeId", "=", productTypeId)
: undefined;
const condRegisteredBranchId = registeredBranchId
? eb("registeredBranchId", "=", registeredBranchId).or("registeredBranchId", "is", null)
: undefined;
const or: Prisma.Sql[] = []; return eb.and(
const and: Prisma.Sql[] = []; [condStatus, condQuery, condProductTypeId, condRegisteredBranchId].filter((v) => !!v),
if (query) or.push(Prisma.sql`"name" LIKE ${`%${query}%`}`);
if (status) and.push(Prisma.sql`"status" = ${status}::"Status"`);
if (productTypeId) {
and.push(Prisma.sql`"productTypeId" = ${productTypeId}`);
}
if (registeredBranchId) {
and.push(
Prisma.sql`("registeredBranchId" = ${registeredBranchId} OR "registeredBranchId" IS NULL)`,
); );
} });
const where = Prisma.sql` const record = await union
${or.length > 0 || and.length > 0 ? Prisma.sql`WHERE ` : Prisma.empty} .selectAll()
${or.length > 0 ? Prisma.join(or, " OR ", "(", ")") : Prisma.empty} .orderBy("statusOrder asc")
${or.length > 0 && and.length > 0 ? Prisma.sql` AND ` : Prisma.empty} .orderBy("createdAt asc")
${and.length > 0 ? Prisma.join(and, " AND ", "(", ")") : Prisma.empty} .limit(pageSize)
`; .offset((page - 1) * pageSize)
console.log(where.sql); .execute();
const count = await union
const [result, [{ total }]] = await prisma.$transaction([ .select((eb) => eb.fn.count<number>("id").as("total"))
prisma.$queryRaw<((Product & { type: "product" }) | (Service & { type: "service" }))[]>` .executeTakeFirst();
SELECT * FROM (${union}) AS "ProductService"
${where}
ORDER BY "ProductService"."statusOrder" ASC, "ProductService"."createdAt" ASC
LIMIT ${pageSize} OFFSET ${(page - 1) * pageSize}
`,
prisma.$queryRaw<[{ total: number }]>`
SELECT COUNT(*) AS "total" FROM (${union}) as "ProductService"
${where}
`,
]);
const work = await prisma.work.findMany({ const work = await prisma.work.findMany({
where: { serviceId: { in: result.flatMap((v) => (v.type === "service" ? v.id : [])) } }, where: { serviceId: { in: record.flatMap((v) => (v.type === "service" ? v.id : [])) } },
}); });
return { return {
result: result.map((v) => result: record.map((v) =>
v.type === "service" ? { ...v, work: work.filter((w) => w.serviceId === v.id) || [] } : v, v.type === "service" ? { ...v, work: work.filter((w) => w.serviceId === v.id) || [] } : v,
), ),
page, page,
pageSize, pageSize,
total: +String(total), total: +String(count?.total || 0),
}; };
} }
} }