hrms-edm/Services/server/src/controllers/fileController.ts

321 lines
9 KiB
TypeScript
Raw Normal View History

import {
Controller,
2023-11-20 12:03:28 +07:00
Delete,
FormField,
2023-11-20 11:08:25 +07:00
Get,
2023-11-20 14:13:02 +07:00
Patch,
Path,
Post,
Request,
Route,
Security,
SuccessResponse,
Tags,
UploadedFile,
} from "tsoa";
2023-11-17 09:03:31 +07:00
import esClient from "../elasticsearch";
import minioClient from "../storage";
import HttpStatusCode from "../interfaces/http-status";
import { pathExist } from "../utils/minio";
import HttpError from "../interfaces/http-error";
2023-11-20 11:07:57 +07:00
import { EhrFile } from "../interfaces/ehr-fs";
2023-11-17 09:03:31 +07:00
2023-11-21 09:34:38 +07:00
@Route("/cabinet/{cabinetName}/drawer/{drawerName}/folder/{folderName}/file")
2023-11-17 09:03:31 +07:00
export class FileController extends Controller {
2023-11-21 09:34:38 +07:00
@Post("/")
@Tags("File")
@Security("bearerAuth")
@SuccessResponse(HttpStatusCode.CREATED)
public async uploadFile(
2023-11-20 11:07:57 +07:00
@Request() request: { user: { preferred_username: string } },
@UploadedFile() file: Express.Multer.File,
@FormField() title: string,
@FormField() description: string,
2023-11-20 11:07:57 +07:00
@FormField() keyword: string,
@FormField() category: string,
@Path() cabinetName: string,
@Path() drawerName: string,
@Path() folderName: string,
) {
2023-11-17 09:03:31 +07:00
const filename = Buffer.from(file.originalname, "latin1").toString("utf-8");
const pathname = `${cabinetName}/${drawerName}/${folderName}/${filename}`;
if (!(await pathExist(`${cabinetName}/${drawerName}/${folderName}/`))) {
throw new HttpError(
HttpStatusCode.PRECONDITION_FAILED,
"Cabinet, drawer or folder cannot be found.",
);
}
const info = await minioClient
.putObject("ehr", pathname, file.buffer, file.size, {
"Content-Type": file.mimetype,
createdAt: new Date().toISOString(),
createdBy: request.user.preferred_username,
})
2023-11-20 11:07:57 +07:00
.catch((e) => console.error(e));
2023-11-17 09:03:31 +07:00
2023-11-20 11:07:57 +07:00
if (!info) throw new Error("Object storage error occured.");
const search = await esClient.search<EhrFile & { attachment: Record<string, string> }>({
index: "ehr-api-client",
query: {
match: {
pathname: pathname,
},
},
});
const exist = search.hits.hits.find((v) => v._source?.pathname === pathname);
const metadata: Partial<EhrFile> = {
pathname,
fileName: filename,
fileSize: file.size,
fileType: file.mimetype,
title: title,
description: description,
category: category.split(","),
keyword: keyword.split(","),
};
if (!exist) {
await esClient.index({
pipeline: "attachment",
index: "ehr-api-client",
document: {
data: Buffer.from(file.buffer).toString("base64"),
createdAt: new Date().toISOString(),
createdBy: request.user.preferred_username,
updatedAt: new Date().toISOString(),
updatedBy: request.user.preferred_username,
...metadata,
},
});
} else {
await esClient.delete({ index: exist._index, id: exist._id });
await esClient.index({
pipeline: "attachment",
index: "ehr-api-client",
document: {
data: Buffer.from(file.buffer).toString("base64"),
2023-11-20 11:07:57 +07:00
createdAt: exist._source?.createdAt,
createdBy: exist._source?.createdBy,
updatedAt: new Date().toISOString(),
updatedBy: request.user.preferred_username,
...metadata,
2023-11-17 09:03:31 +07:00
},
});
}
2023-11-17 09:03:31 +07:00
return this.setStatus(HttpStatusCode.CREATED);
2023-11-17 09:03:31 +07:00
}
2023-11-20 11:08:25 +07:00
2023-11-21 09:34:38 +07:00
@Get("/")
2023-11-20 11:08:25 +07:00
@Tags("File")
@SuccessResponse(HttpStatusCode.OK)
public async getFile(
@Path() cabinetName: string,
@Path() drawerName: string,
@Path() folderName: string,
2023-11-20 16:23:17 +07:00
): Promise<EhrFile[]> {
2023-11-20 11:08:25 +07:00
const search = await esClient.search<
EhrFile & {
attachment: Record<string, string>;
}
>({
index: "ehr-api-client",
query: {
prefix: {
pathname: `${cabinetName}/${drawerName}/${folderName}/`,
},
},
});
2023-11-20 11:50:18 +07:00
// Use flatMap for return type only. Filter does not change type after filter out undefined or null
2023-11-20 11:08:25 +07:00
const records = search.hits.hits
.map((v) => {
2023-11-20 11:50:18 +07:00
if (!v._source) return;
2023-11-20 14:13:19 +07:00
const { attachment, ...rest } = v._source;
2023-11-20 11:08:25 +07:00
2023-11-20 14:13:19 +07:00
return rest;
2023-11-20 11:08:25 +07:00
})
2023-11-20 11:50:18 +07:00
.flatMap((v) => (v ? [v] : []));
2023-11-20 11:08:25 +07:00
return records;
}
2023-11-20 12:03:28 +07:00
2023-11-21 09:34:38 +07:00
@Patch("/{fileName}")
2023-11-20 14:13:02 +07:00
@Tags("File")
@Security("bearerAuth")
@SuccessResponse(HttpStatusCode.OK)
public async updateFile(
@Request() request: { user: { preferred_username: string } },
@Path() cabinetName: string,
@Path() drawerName: string,
@Path() folderName: string,
@Path() fileName: string,
@UploadedFile() file?: Express.Multer.File,
@FormField() title?: string,
@FormField() description?: string,
@FormField() keyword?: string,
@FormField() category?: string,
) {
const search = await esClient.search<EhrFile & { attachment: Record<string, string> }>({
index: "ehr-api-client",
query: {
match: {
pathname: `${cabinetName}/${drawerName}/${folderName}/${fileName}`,
},
},
});
if (search && search.hits.hits.length === 0) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "Not found");
}
const data = search.hits.hits[0];
if (!file) {
const esResult = await esClient
.update({
index: "ehr-api-client",
id: data._id,
doc: {
title,
description,
keyword: keyword?.split(","),
category: category?.split(","),
updatedAt: new Date().toISOString(),
updatedBy: request.user.preferred_username,
},
})
.catch((e) => console.error(e));
if (!esResult) throw new Error("An error occured, cannot perform this action.");
} else {
const filename = Buffer.from(file.originalname, "latin1").toString("utf-8");
const pathname = `${cabinetName}/${drawerName}/${folderName}/${filename}`;
await minioClient.removeObject(
"ehr",
`${cabinetName}/${drawerName}/${folderName}/${fileName}`,
);
const info = await minioClient
.putObject("ehr", pathname, file.buffer, file.size, {
"Content-Type": file.mimetype,
createdAt: new Date().toISOString(),
createdBy: request.user.preferred_username,
})
.catch((e) => console.error(e));
if (!info) throw new Error("Object storage error occured.");
await esClient.delete({ index: data._index, id: data._id });
await esClient.index({
pipeline: "attachment",
index: "ehr-api-client",
document: {
data: Buffer.from(file.buffer).toString("base64"),
pathname,
fileName: filename,
fileSize: file.size,
fileType: file.mimetype,
title: title,
description: description,
category: category?.split(","),
keyword: keyword?.split(","),
createdAt: data._source?.createdAt,
createdBy: data._source?.createdBy,
updatedAt: new Date().toISOString(),
updatedBy: request.user.preferred_username,
},
});
}
return this.setStatus(HttpStatusCode.NO_CONTENT);
}
2023-11-21 09:34:38 +07:00
@Delete("/{fileName}")
2023-11-20 12:03:28 +07:00
@Tags("File")
2023-11-20 12:04:26 +07:00
@Security("bearerAuth")
2023-11-20 12:03:28 +07:00
@SuccessResponse(HttpStatusCode.OK)
public async deleteFile(
@Path() cabinetName: string,
@Path() drawerName: string,
@Path() folderName: string,
@Path() fileName: string,
) {
const search = await esClient.search<
EhrFile & {
attachment: Record<string, string>;
}
>({
index: "ehr-api-client",
query: {
match: {
pathname: `${cabinetName}/${drawerName}/${folderName}/${fileName}`,
},
},
});
if (search && search.hits.hits.length === 0) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "Not found");
}
const esResult = await esClient
.delete({
index: "ehr-api-client",
id: search.hits.hits[0]._id,
})
.catch((e) => console.error(e));
if (!esResult) throw new Error("An error occured, cannot perform this action.");
await minioClient.removeObject("ehr", `${cabinetName}/${drawerName}/${folderName}/${fileName}`);
return this.setStatus(HttpStatusCode.NO_CONTENT);
}
2023-11-22 12:58:45 +07:00
@Get("/{fileName}")
@Tags("File")
@SuccessResponse(HttpStatusCode.OK)
public async downloadFile(
@Path() cabinetName: string,
@Path() drawerName: string,
@Path() folderName: string,
@Path() fileName: string,
) {
const search = await esClient.search<EhrFile & { attachment: Record<string, string> }>({
index: "ehr-api-client",
query: {
match: {
pathname: `${cabinetName}/${drawerName}/${folderName}/${fileName}`,
},
},
});
if (search && search.hits.hits.length === 0) {
throw new HttpError(HttpStatusCode.NOT_FOUND, "Not found");
}
const data = search.hits.hits[0]._source;
if (!data) {
throw new HttpError(HttpStatusCode.INTERNAL_SERVER_ERROR, "Found data but no info.");
}
const { attachment, ...rest } = data;
return {
...rest,
download: await minioClient.presignedGetObject(
"ehr",
`${cabinetName}/${drawerName}/${folderName}/${fileName}`,
),
};
}
2023-11-17 09:03:31 +07:00
}