refactor: use helper function

This commit is contained in:
Methapon Metanipat 2024-09-12 10:39:58 +07:00
parent da8e3f5e44
commit 155962b996

View file

@ -15,7 +15,6 @@ import {
} from "tsoa"; } from "tsoa";
import { RequestWithUser } from "../interfaces/user"; import { RequestWithUser } from "../interfaces/user";
import prisma from "../db"; import prisma from "../db";
import minio, { deleteFolder } from "../services/minio";
import HttpStatus from "../interfaces/http-status"; import HttpStatus from "../interfaces/http-status";
import HttpError from "../interfaces/http-error"; import HttpError from "../interfaces/http-error";
import { isSystem } from "../utils/keycloak"; import { isSystem } from "../utils/keycloak";
@ -25,13 +24,9 @@ import {
createPermCondition, createPermCondition,
} from "../services/permission"; } from "../services/permission";
import { filterStatus } from "../services/prisma"; import { filterStatus } from "../services/prisma";
import { fileLocation, listFile } from "../utils/minio"; import { deleteFile, deleteFolder, fileLocation, getFile, listFile, setFile } from "../utils/minio";
import { notFoundError, relationError } from "../utils/error";
if (!process.env.MINIO_BUCKET) {
throw Error("Require MinIO bucket.");
}
const MINIO_BUCKET = process.env.MINIO_BUCKET;
const MANAGE_ROLES = [ const MANAGE_ROLES = [
"system", "system",
"head_of_admin", "head_of_admin",
@ -182,9 +177,7 @@ export class CustomerController extends Controller {
prisma.employee.count({ where: { customerBranch: { customerId } } }), prisma.employee.count({ where: { customerBranch: { customerId } } }),
]); ]);
if (!record) { if (!record) throw notFoundError("Customer");
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
}
return Object.assign(record, { _count: { employee: countEmployee } }); return Object.assign(record, { _count: { employee: countEmployee } });
} }
@ -192,9 +185,7 @@ export class CustomerController extends Controller {
@Security("keycloak", MANAGE_ROLES) @Security("keycloak", MANAGE_ROLES)
async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) { async create(@Request() req: RequestWithUser, @Body() body: CustomerCreate) {
// NOTE: handle empty string // NOTE: handle empty string
if (!body.registeredBranchId) { if (!body.registeredBranchId) body.registeredBranchId = undefined;
body.registeredBranchId = undefined;
}
const [branch] = await prisma.$transaction([ const [branch] = await prisma.$transaction([
prisma.branch.findFirst({ prisma.branch.findFirst({
@ -203,13 +194,7 @@ export class CustomerController extends Controller {
}), }),
]); ]);
if (!!body.registeredBranchId && !branch) { if (!!body.registeredBranchId && !branch) throw relationError("Branch");
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
if (body.registeredBranchId !== undefined && branch) { if (body.registeredBranchId !== undefined && branch) {
await permissionCheck(req.user, branch); await permissionCheck(req.user, branch);
@ -262,9 +247,7 @@ export class CustomerController extends Controller {
@Request() req: RequestWithUser, @Request() req: RequestWithUser,
@Body() body: CustomerUpdate, @Body() body: CustomerUpdate,
) { ) {
if (body.registeredBranchId === "") { if (body.registeredBranchId === "") body.registeredBranchId = undefined;
body.registeredBranchId = undefined;
}
const customer = await prisma.customer.findUnique({ const customer = await prisma.customer.findUnique({
where: { id: customerId }, where: { id: customerId },
@ -275,9 +258,7 @@ export class CustomerController extends Controller {
}, },
}); });
if (!customer) { if (!customer) throw notFoundError("Branch");
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found.", "customerNotFound");
}
const [branch] = await prisma.$transaction([ const [branch] = await prisma.$transaction([
prisma.branch.findFirst({ prisma.branch.findFirst({
@ -286,13 +267,7 @@ export class CustomerController extends Controller {
}), }),
]); ]);
if (!!body.registeredBranchId && !branch) { if (!!body.registeredBranchId && !branch) throw relationError("Branch");
throw new HttpError(
HttpStatus.BAD_REQUEST,
"Branch cannot be found.",
"relationBranchNotFound",
);
}
if (customer.registeredBranch) { if (customer.registeredBranch) {
await permissionCheck(req.user, customer.registeredBranch); await permissionCheck(req.user, customer.registeredBranch);
@ -351,24 +326,30 @@ export class CustomerController extends Controller {
return await prisma.customer return await prisma.customer
.delete({ where: { id: customerId } }) .delete({ where: { id: customerId } })
.then( .then((data) => deleteFolder(`customer/${customerId}`).then(() => data));
async (data) => await deleteFolder(MINIO_BUCKET, `customer/${customerId}`).then(() => data),
);
} }
} }
@Route("api/v1/customer/{customerId}/image") @Route("api/v1/customer/{customerId}/image")
@Tags("Customer") @Tags("Customer")
export class CustomerImageController extends Controller { export class CustomerImageController extends Controller {
private async checkPermission(user: RequestWithUser["user"], id: string) {
const data = await prisma.customer.findUnique({
include: {
registeredBranch: {
include: branchRelationPermInclude(user),
},
},
where: { id },
});
if (!data) throw notFoundError("Customer");
await permissionCheck(user, data.registeredBranch);
}
@Get() @Get()
@Security("keycloak") @Security("keycloak")
async listImage(@Path() customerId: string) { async listImage(@Request() req: RequestWithUser, @Path() customerId: string) {
const customer = await prisma.customer.findUnique({ await this.checkPermission(req.user, customerId);
where: { id: customerId },
});
if (!customer) {
throw new HttpError(HttpStatus.NOT_FOUND, "Customer cannot be found", "customerNotFound");
}
return await listFile(fileLocation.customer.img(customerId)); return await listFile(fileLocation.customer.img(customerId));
} }
@ -379,11 +360,7 @@ export class CustomerImageController extends Controller {
@Path() name: string, @Path() name: string,
) { ) {
return req.res?.redirect( return req.res?.redirect(
await minio.presignedGetObject( await getFile(fileLocation.customer.img(customerId, name), 12 * 60 * 60),
MINIO_BUCKET,
fileLocation.customer.img(customerId, name),
12 * 60 * 60,
),
); );
} }
@ -394,25 +371,9 @@ export class CustomerImageController extends Controller {
@Path() customerId: string, @Path() customerId: string,
@Path() name: string, @Path() name: string,
) { ) {
const customer = await prisma.customer.findUnique({ await this.checkPermission(req.user, customerId);
where: { id: customerId },
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
},
});
if (!customer) {
throw new HttpError(HttpStatus.NOT_FOUND, "Image cannot be found", "imageNotFound");
}
console.log(customer.registeredBranch);
await permissionCheck(req.user, customer.registeredBranch);
return req.res?.redirect( return req.res?.redirect(
await minio.presignedPutObject( await setFile(fileLocation.customer.img(customerId, name), 12 * 60 * 60),
MINIO_BUCKET,
fileLocation.customer.img(customerId, name),
12 * 60 * 60,
),
); );
} }
@ -423,20 +384,7 @@ export class CustomerImageController extends Controller {
@Path() customerId: string, @Path() customerId: string,
@Path() name: string, @Path() name: string,
) { ) {
const customer = await prisma.customer.findUnique({ await this.checkPermission(req.user, customerId);
where: { id: customerId }, await deleteFile(fileLocation.customer.img(customerId, name));
include: {
registeredBranch: {
include: branchRelationPermInclude(req.user),
},
},
});
if (!customer) {
throw new HttpError(HttpStatus.NOT_FOUND, "Image cannot be found", "imageNotFound");
}
await permissionCheck(req.user, customer.registeredBranch);
await minio.removeObject(MINIO_BUCKET, fileLocation.customer.img(customerId, name), {
forceDelete: true,
});
} }
} }