113 lines
2.8 KiB
TypeScript
113 lines
2.8 KiB
TypeScript
import {
|
|
Body,
|
|
Controller,
|
|
Delete,
|
|
Get,
|
|
Path,
|
|
Post,
|
|
Put,
|
|
Query,
|
|
Request,
|
|
Route,
|
|
Security,
|
|
Tags,
|
|
} from "tsoa";
|
|
import { RequestWithUser } from "../interfaces/user";
|
|
import prisma from "../db";
|
|
import { Prisma } from "@prisma/client";
|
|
import { queryOrNot } from "../utils/relation";
|
|
import { notFoundError } from "../utils/error";
|
|
|
|
type BusinessTypePayload = {
|
|
name: string;
|
|
nameEN: string;
|
|
};
|
|
|
|
@Route("api/v1/business-type")
|
|
@Tags("Business Type")
|
|
export class businessTypeController extends Controller {
|
|
@Get()
|
|
@Security("keycloak")
|
|
async getList(
|
|
@Request() req: RequestWithUser,
|
|
@Query() query: string = "",
|
|
@Query() page: number = 1,
|
|
@Query() pageSize: number = 30,
|
|
) {
|
|
const where = {
|
|
OR: queryOrNot<Prisma.BusinessTypeWhereInput[]>(query, [
|
|
{ name: { contains: query, mode: "insensitive" } },
|
|
{ nameEN: { contains: query, mode: "insensitive" } },
|
|
]),
|
|
} satisfies Prisma.BusinessTypeWhereInput;
|
|
|
|
const [result, total] = await prisma.$transaction([
|
|
prisma.businessType.findMany({
|
|
where,
|
|
take: pageSize,
|
|
skip: (page - 1) * pageSize,
|
|
}),
|
|
prisma.businessType.count({ where }),
|
|
]);
|
|
|
|
return { result, page, pageSize, total };
|
|
}
|
|
|
|
@Post()
|
|
@Security("keycloak")
|
|
async createBusinessType(@Request() req: RequestWithUser, @Body() body: BusinessTypePayload) {
|
|
return await prisma.businessType.create({
|
|
data: {
|
|
...body,
|
|
createdByUserId: req.user.sub,
|
|
updatedByUserId: req.user.sub,
|
|
},
|
|
});
|
|
}
|
|
|
|
@Get(":businessTypeId")
|
|
@Security("keycloak")
|
|
async getBusinessTypeById(@Path() businessTypeId: string) {
|
|
return await prisma.businessType.findUnique({
|
|
where: { id: businessTypeId },
|
|
});
|
|
}
|
|
|
|
@Put(":businessTypeId")
|
|
@Security("keycloak")
|
|
async updateBusinessType(
|
|
@Request() req: RequestWithUser,
|
|
@Path() businessTypeId: string,
|
|
@Body() body: BusinessTypePayload,
|
|
) {
|
|
return await prisma.$transaction(async (tx) => {
|
|
const record = await tx.businessType.findUnique({
|
|
where: { id: businessTypeId },
|
|
});
|
|
|
|
if (!record) throw notFoundError("BusinessType");
|
|
return await tx.businessType.update({
|
|
where: { id: businessTypeId },
|
|
data: {
|
|
...body,
|
|
updatedByUserId: req.user.sub,
|
|
},
|
|
});
|
|
});
|
|
}
|
|
|
|
@Delete(":businessTypeId")
|
|
@Security("keycloak")
|
|
async deleteBusinessType(@Path() businessTypeId: string) {
|
|
return await prisma.$transaction(async (tx) => {
|
|
const record = await tx.businessType.findUnique({
|
|
where: { id: businessTypeId },
|
|
});
|
|
|
|
if (!record) throw notFoundError("BusinessType");
|
|
return await tx.businessType.delete({
|
|
where: { id: businessTypeId },
|
|
});
|
|
});
|
|
}
|
|
}
|