feat: file move and delete endpoint

This commit is contained in:
Methapon2001 2023-12-12 12:01:56 +07:00
parent 8fbeda892b
commit 07d97a9091
No known key found for this signature in database
GPG key ID: 849924FEF46BD132
4 changed files with 520 additions and 44 deletions

View file

@ -1,9 +1,12 @@
import { Body, Controller, Delete, Example, Post, Put, Route, SuccessResponse } from "tsoa";
import { Body, Controller, Delete, Example, Post, Put, Route, SuccessResponse, Tags } from "tsoa";
import minioClient from "../minio";
import esClient from "../elasticsearch";
import HttpError from "../interfaces/http-error";
import HttpStatusCode from "../interfaces/http-status";
import { StorageFile, StorageFolder } from "../interfaces/storage-fs";
import { copyCond } from "../utils/minio";
if (!process.env.MINIO_BUCKET) throw Error("Default MinIO bucket must be specified.");
@ -20,35 +23,73 @@ interface ListRequestBody {
path: string[];
}
interface CreateFolderBody {
interface FolderBody {
/** @example ["แฟ้ม 1", "แฟ้ม 2"] */
path: string[];
/** @example "แฟ้ม 3" */
name: string;
}
interface PutFolderBody {
from: {
/** @example ["แฟ้ม 1", "แฟ้ม 2"] */
path: string[];
/** @example "แฟ้ม 3" */
name: string;
};
to: {
/** @example ["แฟ้ม 1", "แฟ้ม 2"] */
path: string[];
/** @example "แฟ้ม 3 แก้ไข" */
name: string;
};
}
interface DeleteFolderBody {
/** @example ["แฟ้ม 1", "แฟ้ม 2", "แฟ้ม 3 แก้ไข"] */
path: string[];
}
interface CreateFileBody {
interface FileBody {
/** @example ["แฟ้ม 1", "แฟ้ม 2", "แฟ้ม 3"] */
path: string[];
/** @example "ไฟล์ 1.xlsx" */
file: string;
/** @example "การเงิน" */
title?: string;
/** @example "การเงิน" */
description?: string;
/** @example ["การเงิน", "รายงาน"] */
category?: string[];
/** @example ["การเงิน", "รายรับ", "รายจ่าย"] */
keyword?: string[];
}
interface PutFileBody extends Omit<FileBody, "file" | "path"> {
/** หากต้องการอัพโหลดไฟล์ด้วยให้ส่งค่าเป็นจริง */
from: {
/** @example ["แฟ้ม 1", "แฟ้ม 2", "แฟ้ม 3"] */
path: string[];
/** @example "ไฟล์ 1.xlsx" */
file: string;
};
to?: {
/** @example ["แฟ้ม 1", "แฟ้ม 2", "แฟ้ม 3"] */
path: string[];
/** @example "ไฟล์ 1 แก้ไข.xlsx" */
file: string;
};
/** @example false */
upload?: boolean;
}
interface DeleteFileBody {
/** @example ["แฟ้ม 1", "แฟ้ม 2", "แฟ้ม 3"] */
path: string[];
/** @example "ไฟล์ 1 แก้ไข.xlsx" */
file: string;
}
async function listFolder(path: string[]) {
const list = await new Promise<{ pathname: string; name: string }[]>((resolve, reject) => {
const item: { pathname: string; name: string }[] = [];
@ -90,13 +131,9 @@ async function listFolder(path: string[]) {
async function listFile(path: string[]) {
const result = await esClient
.search<StorageFile & { attachment: Record<string, string> }>({
index: DEFAULT_INDEX!,
index: DEFAULT_INDEX,
sort: [{ pathname: "asc" }],
query: {
match: {
path: path.join("/") + "/",
},
},
query: { match: { path: path.join("/") + "/" } },
size: 10000,
})
.then((r) => r.hits.hits);
@ -114,8 +151,12 @@ async function listFile(path: string[]) {
}
async function checkPathExist(bucket: string, path: string) {
return await checkFileExist(bucket, `${path}/.keep`);
}
async function checkFileExist(bucket: string, pathname: string) {
return Boolean(
await minioClient.statObject(bucket, `${path}/.keep`).catch((e) => {
await minioClient.statObject(bucket, pathname).catch((e) => {
if (e.code === "NotFound") return false;
console.error(`Storage Error: ${e}`);
throw new Error(MINIO_ERROR_MESSAGE);
@ -158,6 +199,7 @@ export class StorageController extends Controller {
updatedBy: "admin",
},
])
@Tags("Storage Folder", "Storage File")
public async getList(@Body() body: ListRequestBody) {
const path = body.path.filter(Boolean);
@ -166,8 +208,9 @@ export class StorageController extends Controller {
}
@Post("folder")
@Tags("Storage Folder")
@SuccessResponse(HttpStatusCode.NO_CONTENT, "สำเร็จ")
public async postFolder(@Body() body: CreateFolderBody) {
public async postFolder(@Body() body: FolderBody) {
const { path, name } = body;
if (!(await checkPathExist(DEFAULT_BUCKET, path.join("/")))) {
@ -196,6 +239,8 @@ export class StorageController extends Controller {
* Folder Folder (Path) Folder (Path)
*/
@Put("folder")
@Tags("Storage Folder")
@SuccessResponse(HttpStatusCode.NO_CONTENT, "สำเร็จ")
public async moveFolder(@Body() body: PutFolderBody) {
const src = `${body.from.path.join("/")}/${body.from.name}`;
const dst = `${body.to.path.join("/")}/${body.to.name}`;
@ -284,6 +329,7 @@ export class StorageController extends Controller {
* Folder File
*/
@Delete("folder")
@Tags("Storage Folder")
@SuccessResponse(HttpStatusCode.NO_CONTENT, "สำเร็จ")
public async deleteStorage(@Body() body: DeleteFolderBody) {
await new Promise<void>((resolve, reject) => {
@ -304,8 +350,9 @@ export class StorageController extends Controller {
* URL
*/
@Post("file")
@Tags("Storage File")
@SuccessResponse(HttpStatusCode.NO_CONTENT, "สำเร็จ")
public async postFile(@Body() body: CreateFileBody) {
public async postFile(@Body() body: FileBody) {
const { path, file } = body;
if (!(await checkPathExist(DEFAULT_BUCKET, path.join("/")))) {
@ -363,4 +410,131 @@ export class StorageController extends Controller {
return { ...metadata, uploadUrl: presignedUrl };
}
@Put("file")
@Tags("Storage File")
@SuccessResponse(HttpStatusCode.NO_CONTENT, "สำเร็จ")
public async moveFile(@Body() body: PutFileBody) {
const search = await esClient
.search<StorageFile & { attachment: Record<string, any> }>({
index: DEFAULT_INDEX,
query: {
match: { pathname: body.from.path.join("/") + `/${body.from.file}` },
},
})
.catch((e) => console.error(`ElasticSearch Error: ${e}`));
if (!search) {
throw new Error("เกิดข้อผิดพลาดกับระบบฐานข้อมูล กรุณาลองใหม่ในภายหลัง");
}
if (search && search.hits.hits.length === 0) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบไฟล์ดังกล่าว");
}
if (!(await checkFileExist(DEFAULT_BUCKET, body.from.path.join("/") + `/${body.from.file}`))) {
await esClient.delete({
index: DEFAULT_INDEX,
id: search.hits.hits[0]._id,
});
throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบไฟล์ดังกล่าว");
}
if (body.to && !(await checkPathExist(DEFAULT_BUCKET, body.to.path.join("/")))) {
throw new HttpError(HttpStatusCode.PRECONDITION_FAILED, "ไม่พบตำแหน่งที่ต้องการย้าย");
}
if (
body.to &&
(await checkFileExist(DEFAULT_BUCKET, body.to.path.join("/") + `/${body.to.file}`))
) {
throw new HttpError(
HttpStatusCode.PRECONDITION_FAILED,
"พบไฟล์ในต้ำแหน่งปลายทาง ไม่สามารถย้ายได้",
);
}
if (!search.hits.hits[0]._source) {
// This should not possible.
// Just in case the result found with no associated data.
await esClient.delete({
index: DEFAULT_INDEX,
id: search.hits.hits[0]._id,
});
throw new Error("ไม่พบข้อมูลในฐานข้อมูล");
}
const id = search.hits.hits[0]._id;
const { to, from, upload, ...metadata } = body;
if (from && to) {
const src = [DEFAULT_BUCKET, ...from.path, ""].join("/") + from.file;
const dst = to.path.join("/") + `/${to.file}`;
const result = await minioClient.copyObject(DEFAULT_BUCKET, dst, src, copyCond).catch((e) => {
console.error(`MinIO Error: ${e}`);
throw new Error("เกิดข้อผิดพลาด ไม่สามารถย้ายไฟล์ได้");
});
if (result) {
await esClient
.update({
index: DEFAULT_INDEX,
id: id,
doc: {
...metadata,
path: to.path.join("/") + "/",
pathname: dst,
updatedAt: new Date().toISOString(),
updatedBy: "n/a",
},
refresh: "wait_for",
})
.then(async () => await minioClient.removeObject(DEFAULT_INDEX, src))
.catch((e) => console.error(`ElasticSearch Error: ${e}`));
if (upload) {
const presignedUrl = await minioClient.presignedPutObject(DEFAULT_BUCKET, dst);
return { uploadUrl: presignedUrl };
}
}
}
if (from) {
await esClient
.update({
index: DEFAULT_INDEX,
id: id,
doc: {
...metadata,
updatedAt: new Date().toISOString(),
updatedBy: "n/a",
},
refresh: "wait_for",
})
.catch((e) => console.error(`ElasticSearch Error: ${e}`));
if (upload) {
const src = from.path.join("/") + `/${from.file}`;
const presignedUrl = await minioClient.presignedPutObject(DEFAULT_BUCKET, src);
return { uploadUrl: presignedUrl };
}
}
return this.setStatus(HttpStatusCode.NO_CONTENT);
}
@Delete("file")
@Tags("Storage File")
@SuccessResponse(HttpStatusCode.NO_CONTENT, "สำเร็จ")
public async deleteFile(@Body() body: DeleteFileBody) {
const pathname = body.path.join("/") + body.file;
await minioClient
.removeObject(DEFAULT_BUCKET, pathname)
.catch((e) => console.error(`MinIO Error: ${e}`));
await esClient
.deleteByQuery({
index: DEFAULT_INDEX,
query: { match: { pathname } },
})
.catch((e) => console.error(`ElasticSearch Error: ${e}`));
return this.setStatus(HttpStatusCode.NO_CONTENT);
}
}