This commit is contained in:
2026-06-10 14:17:06 +07:00
parent 8d516fb515
commit 04a4e2cf98
5 changed files with 323 additions and 249 deletions

View File

@ -1,223 +1,171 @@
import { Response, NextFunction } from "express";
import { NextFunction, Response } from "express";
import { Request } from "express-jwt";
import { ReturnHelper } from "../../helpers/express/return";
import { UploadedFile } from "express-fileupload";
import fs from "fs"; // Import fs module to check if directory exists
import Joi from "joi";
import { ILogObj, Logger } from "tslog";
import CommonHelper from "../../helpers/common";
import { ReturnHelper } from "../../helpers/express/return";
import { Language } from "../../langs/lang";
import fileUpload from "express-fileupload";
import { v4 as uuidv4 } from 'uuid';
import fs from "fs";
import path from "path";
import config from "config";
import Thirdparty from "../../helpers/thirdparty";
import JwtHelper from "../../helpers/jwt";
const log: Logger<ILogObj> = new Logger({ name: '[FileController]', type: 'pretty' });
const STORAGE_DIR = 'assets/saude/';
const log: Logger<ILogObj> = new Logger({
name: "[FileController]",
type: "pretty",
});
export class FileController {
static async upload(req: Request, res: Response, next: NextFunction): Promise<Response> {
/* #swagger.tags = ['Handle File']
#swagger.security = [{ "bearerAuth": [] }]
#swagger.consumes = ['multipart/form-data']
#swagger.requestBody = {
required: true,
content: {
"multipart/form-data": {
schema: {
type: "object",
properties: {
file: {
type: "string",
format: "binary",
description: "Image file (max 1MB, jpg/png/webp)"
},
},
required: ["file"]
}
}
}
}
*/
try {
// Check if file exists
if (!req.files || !req.files.file) {
return ReturnHelper.errorResponse(res, 400, 404, Language.lang.failed_insert, "File not found");
}
const file = req.files.file as fileUpload.UploadedFile;
// Validate file size (max 1MB)
const maxSize = 10 * 1024 * 1024; // 10MB
if (file.size > maxSize) {
return ReturnHelper.errorResponse(
res,
400,
400,
Language.lang.failed_insert,
"File size exceeds 10MB limit"
);
}
// Validate file type
const allowedMimes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/svg+xml', 'image/svg'];
if (!allowedMimes.includes(file.mimetype)) {
return ReturnHelper.errorResponse(res, 400, 400, Language.lang.failed_insert, "Invalid file type. Only JPG, PNG, WEBP, and SVG are allowed");
}
const ext = file.name.split('.');
const name = uuidv4() + '.' + ext[ext.length - 1];
const result: { file: string } = {
file: "",
};
const folder_path = STORAGE_DIR;
const file_path = path.join(folder_path, name);
// Create directory if it doesn't exist
if (!fs.existsSync(folder_path)) {
fs.mkdirSync(folder_path, { recursive: true });
}
// Move file to destination
await file.mv(file_path);
result.file = name;
log.info(`File uploaded successfully: ${file_path}`);
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_insert, result);
} catch (e: unknown) {
// Proper error logging to avoid tslog serialization issues
if (e instanceof Error) {
log.error("File upload failed:", {
message: e.message,
stack: e.stack,
name: e.name
});
return ReturnHelper.errorResponse(res, 500, 500, Language.lang.failed_insert, e.message);
} else {
log.error("File upload failed with unknown error:", String(e));
return ReturnHelper.errorResponse(res, 500, 500, Language.lang.failed_insert, "Unknown error occurred");
static async upload(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
/*
#swagger.tags = ['File']
#swagger.security = [{
"bearerAuth": []
}]
#swagger.requestBody = {
required: true,
content: {
"multipart/form-data": {
schema: {
type: "object",
properties: {
file: {
type: "string",
format: "binary"
}
}
}
}
}
}
}
}
*/
try {
const uploadedFile: UploadedFile | any = req.files.file;
static async delete(req: Request, res: Response, next: NextFunction): Promise<Response> {
/*
#swagger.tags = ['Handle File']
#swagger.security = [{ "bearerAuth": [] }]
#swagger.requestBody = {
required: true,
content: {
"application/json": {
schema: {
type: "object",
properties: {
file_name: { type: "string", description: "File name to delete" }
},
required: ["file_name"]
}
}
}
}
*/
const schema = Joi.object({
file: Joi.object({
name: Joi.string().label("File Name"),
mimetype: Joi.string()
.valid(
"image/jpeg",
"image/png",
"application/pdf",
"application/vnd.ms-excel", // ✅ .xls
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // ✅ .xlsx
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"text/csv", // csv
)
.optional()
.label("File Type"),
size: Joi.number()
.max(10 * 1024 * 1024)
.optional()
.label("File Size"),
})
.optional()
.label("File"),
});
try {
const schema = Joi.object().keys({
file_name: Joi.string().required().label('File Name'),
});
const fileData = {
name: uploadedFile.name,
mimetype: uploadedFile.mimetype,
size: uploadedFile.size,
};
const param: { file_name: string } = await schema.validateAsync(req.body);
let body = await schema.validateAsync({ file: fileData });
if (param.file_name.includes('..') || param.file_name.includes('/') || param.file_name.includes('\\')) {
return ReturnHelper.errorResponse(res, 400, 400, Language.lang.failed_delete, "Invalid file name");
}
const field = {
file: uploadedFile,
application: "saude",
};
const file_path = path.join(STORAGE_DIR, param.file_name);
let url = config.get("service.file") + "upload";
let result = await Thirdparty.UploadFile(url, field, JwtHelper.token(req.auth.data));
console.log("result :", result);
// Check if file exists
if (!fs.existsSync(file_path)) {
return ReturnHelper.errorResponse(res, 404, 404, Language.lang.failed_not_found, "File not found");
}
let data = { file: result.data.file };
return ReturnHelper.successResponseAny(res, 200, Language.lang.success, data);
} catch (e: unknown) {
log.error(e);
const err = e as Error;
// Delete file
fs.unlinkSync(file_path);
return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_view, err.message);
}
}
return ReturnHelper.successResponseAny(res, 200, Language.lang.success_delete, {});
} catch (e: unknown) {
log.error(e);
const err = e as Error;
return ReturnHelper.errorResponse(res, 500, 402, Language.lang.failed_delete, err.message);
static async download(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
/*
#swagger.tags = ['File']
#swagger.security = [{
"bearerAuth": []
}]
#swagger.parameters['name'] = {
in: 'query',
type: 'string'
}
}
static async download(req: Request, res: Response, next: NextFunction): Promise<void | Response> {
/*
#swagger.tags = ['Handle File']
#swagger.security = [{ "bearerAuth": [] }]
#swagger.parameters['name'] = {
in: 'query',
required: true,
type: 'string',
description: 'File name'
}
#swagger.parameters['token'] = {
in: 'query',
required: true,
type: 'string',
description: 'Token'
}
*/
try {
const schema = Joi.object({
name: Joi.string().required().label("File Name"),
token: Joi.string().required().label("Token"),
});
const param: { name: string } = await schema.validateAsync(req.query);
if (param.name.includes('..') || param.name.includes('/') || param.name.includes('\\')) {
return ReturnHelper.errorResponse(res, 400, 400, Language.lang.failed_not_found, "Invalid file name");
}
const file_path = path.join(STORAGE_DIR, param.name);
if (!fs.existsSync(file_path)) {
return ReturnHelper.errorResponse(res, 404, 404, Language.lang.failed_not_found, "File not found");
}
const buffer = fs.readFileSync(file_path);
const fileName = param.name;
const ext = fileName.split(".").pop()?.toLowerCase();
const mimeMap: Record<string, string> = {
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
webp: "image/webp",
gif: "image/gif",
pdf: "application/pdf",
svg: "image/svg+xml",
};
const contentType = mimeMap[ext ?? ""] ?? "application/octet-stream";
res.setHeader("Content-Type", contentType);
res.setHeader("Content-Length", buffer.length);
const isInline = contentType.startsWith("image/") || contentType === "application/pdf";
if (isInline) {
res.setHeader("Content-Disposition", `inline; filename="${encodeURIComponent(fileName)}"`);
} else {
res.setHeader("Content-Disposition", `attachment; filename="${encodeURIComponent(fileName)}"`);
}
return res.end(buffer);
} catch (e: unknown) {
log.error(e);
const err = e as Error;
return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_not_found, err.message);
#swagger.parameters['token'] = {
in: 'query',
required: true,
type: 'string'
}
}
}
*/
try {
// 1⃣ Validasi parameter
const schema = Joi.object({
name: Joi.string().required().label("File Name"),
token: Joi.string().required().label("Token"),
});
const param = await schema.validateAsync(req.query);
// 2⃣ Ambil file dari service-file via SFTP (bukan static URL /file/ yang diarahkan ke frontend)
const url = config.get("service.file") + "download";
const buffer = await Thirdparty.DownloadFile(url, { file: param.name, application: "saude" }, param.token);
// 3⃣ Deteksi ekstensi & MIME type
const fileName = param.name;
const ext = fileName.split(".").pop()?.toLowerCase();
const mimeMap: Record<string, string> = {
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
xls: "application/vnd.ms-excel",
csv: "text/csv",
pdf: "application/pdf",
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
gif: "image/gif",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
zip: "application/zip",
txt: "text/plain",
};
const contentType = mimeMap[ext ?? ""] ?? "application/octet-stream";
// 4⃣ Set header tipe file
res.setHeader("Content-Type", contentType);
res.setHeader("Content-Length", buffer.length);
// 5⃣ Tentukan apakah file perlu auto download
const isInline = contentType.startsWith("image/") || contentType === "application/pdf";
// 🟢 Kalau image/pdf → tampil di browser
// 🔵 Kalau file lain → download otomatis
if (isInline) {
res.setHeader("Content-Disposition", `inline; filename="${encodeURIComponent(fileName)}"`);
} else {
res.setHeader("Content-Disposition", `attachment; filename="${encodeURIComponent(fileName)}"`);
}
// 6⃣ Kirim file ke browser
return res.end(buffer);
} catch (e: unknown) {
log.error(e);
const err = e as Error;
return ReturnHelper.errorResponse(res, 400, 401, Language.lang.failed_not_found, err.message);
}
}
}