From 8fdee84b97b8849d662aa6633156c9abba913b49 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Fri, 17 Nov 2023 17:21:52 +0700 Subject: [PATCH] feat: upload file and elasticsearch index with metadata --- .../server/src/controllers/fileController.ts | 78 +++++++++++++++---- 1 file changed, 63 insertions(+), 15 deletions(-) diff --git a/Prototype/server/src/controllers/fileController.ts b/Prototype/server/src/controllers/fileController.ts index c43947a..1c4dca2 100644 --- a/Prototype/server/src/controllers/fileController.ts +++ b/Prototype/server/src/controllers/fileController.ts @@ -1,24 +1,72 @@ -import { Controller, FormField, Post, Route, UploadedFile } from "tsoa"; -import minioClient from "../storage"; +import { + Controller, + FormField, + Path, + Post, + Request, + Route, + Security, + SuccessResponse, + Tags, + UploadedFile, +} from "tsoa"; 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"; -@Route("/file") +@Route("/cabinet") export class FileController extends Controller { - @Post("/") - public async uploadFile(@UploadedFile() file: Express.Multer.File, @FormField() desc: string) { + @Post("/{cabinetName}/drawer/{drawerName}/folder/{folderName}") + @Tags("File") + @Security("bearerAuth") + @SuccessResponse(HttpStatusCode.CREATED) + public async uploadFile( + @Request() request: any, + @UploadedFile() file: Express.Multer.File, + @FormField() title: string, + @FormField() description: string, + @FormField() keywords: string, + @FormField() categories: string, + @Path() cabinetName: string, + @Path() drawerName: string, + @Path() folderName: string, + ) { const filename = Buffer.from(file.originalname, "latin1").toString("utf-8"); + const pathname = `${cabinetName}/${drawerName}/${folderName}/${filename}`; - console.log( - esClient.search({ - query: { - match_all: {}, + 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, + }) + .catch(() => new Error("Object storage error occured.")); + + if (info) { + await esClient.index({ + pipeline: "attachment", + index: "ehr-api-client", + document: { + data: Buffer.from(file.buffer).toString("base64"), + path: pathname, + title, + description, + keywords, + categories, }, - }), - ); + op_type: "index", + }); + } - minioClient.putObject("ehr", `test_upload_file/${filename}`, file.buffer, file.size, { - "Content-Type": file.mimetype, - }); - return; + return this.setStatus(HttpStatusCode.CREATED); } }