jws-backend/src/controllers/branch/branch-controller.ts

84 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-04-02 09:28:36 +07:00
import { Prisma } from "@prisma/client";
import {
Body,
Controller,
Delete,
Get,
Patch,
Path,
Post,
Query,
Request,
Route,
Security,
Tags,
} from "tsoa";
import prisma from "../../db";
import HttpError from "../../interfaces/http-error";
import HttpStatus from "../../interfaces/http-status";
import { RequestWithUser } from "../../interfaces/user";
@Route("api/branch")
@Tags("Branch")
@Security("keycloak")
export class BranchController extends Controller {
2024-04-02 09:29:20 +07:00
@Get()
async getBranch(
@Query() zipCode?: string,
@Query() query: string = "",
@Query() page: number = 1,
@Query() pageSize: number = 30,
) {
const where = {
OR: [
{ nameEN: { contains: query }, zipCode },
{ nameTH: { contains: query }, zipCode },
{ email: { contains: query }, zipCode },
],
} satisfies Prisma.BranchWhereInput;
const [result, total] = await prisma.$transaction([
prisma.branch.findMany({
include: {
province: true,
district: true,
subDistrict: true,
},
where,
take: pageSize,
skip: (page - 1) * pageSize,
}),
prisma.branch.count({ where }),
]);
return { result, page, pageSize, total };
}
@Get("{branchId}")
async getBranchById(@Path() branchId: string) {
return await prisma.branch.findFirst({
include: {
province: true,
district: true,
subDistrict: true,
},
where: { id: branchId },
});
}
2024-04-02 10:45:37 +07:00
@Delete("{branchId}")
async deleteBranch(@Path() branchId: string) {
const record = await prisma.branch.findFirst({ where: { id: branchId } });
if (!record) {
throw new HttpError(HttpStatus.NOT_FOUND, "Branch cannot be found.");
}
if (record.status === Status.USED) {
throw new HttpError(HttpStatus.FORBIDDEN, "Branch is in used.");
}
return await prisma.branch.delete({ where: { id: branchId } });
}
2024-04-02 09:28:36 +07:00
}