feat: image upload product service

This commit is contained in:
Methapon Metanipat 2024-09-10 15:19:31 +07:00
parent 615ba4e214
commit 8e1a32dcf3
3 changed files with 112 additions and 7 deletions

View file

@ -25,6 +25,7 @@ import {
} from "../services/permission";
import { isSystem } from "../utils/keycloak";
import { filterStatus } from "../services/prisma";
import { deleteFile, fileLocation, getFile, listFile, setFile } from "../utils/minio";
const MANAGE_ROLES = [
"system",
@ -340,3 +341,55 @@ export class ProductController extends Controller {
});
}
}
@Route("api/v1/product/{productId}")
@Tags("Product")
export class ProductFileController extends Controller {
async checkPermission(user: RequestWithUser["user"], id: string) {
const data = await prisma.product.findUnique({
include: {
productGroup: {
include: {
registeredBranch: {
include: branchRelationPermInclude(user),
},
},
},
},
where: { id },
});
if (!data) {
throw new HttpError(HttpStatus.NOT_FOUND, "Product cannot be found.", "productNotFound");
}
await permissionCheck(user, data.productGroup.registeredBranch);
}
@Get("image")
@Security("keycloak")
async listImage(@Request() req: RequestWithUser, @Path() productId: string) {
await this.checkPermission(req.user, productId);
return await listFile(fileLocation.product.img(productId));
}
@Get("image/{name}")
async getImage(@Request() req: RequestWithUser, @Path() productId: string, @Path() name: string) {
return req.res?.redirect(await getFile(fileLocation.product.img(productId, name)));
}
@Put("image/{name}")
@Security("keycloak")
async putImage(@Request() req: RequestWithUser, @Path() productId: string, @Path() name: string) {
if (!req.headers["content-type"]?.startsWith("image/")) {
throw new HttpError(HttpStatus.BAD_REQUEST, "Not a valid image.", "notValidImage");
}
await this.checkPermission(req.user, productId);
return req.res?.redirect(await setFile(fileLocation.product.img(productId, name)));
}
@Delete("image/{name}")
@Security("keycloak")
async delImage(@Request() req: RequestWithUser, @Path() productId: string, @Path() name: string) {
await this.checkPermission(req.user, productId);
return await deleteFile(fileLocation.product.img(productId, name));
}
}