43 lines
987 B
JavaScript
43 lines
987 B
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
const ApiError = require('./ApiError');
|
|
const env = require('../config/env');
|
|
|
|
const attachmentInclude = {
|
|
users: { select: { id: true, full_name: true, employee_code: true } },
|
|
};
|
|
|
|
const sanitizeAttachment = (row) => {
|
|
if (!row) return null;
|
|
const { users, ...rest } = row;
|
|
return {
|
|
...rest,
|
|
uploaded_by_user: users || null,
|
|
users: undefined,
|
|
};
|
|
};
|
|
|
|
const resolveFilePath = (storedPath) => {
|
|
const absolute = path.isAbsolute(storedPath)
|
|
? storedPath
|
|
: path.resolve(env.UPLOAD_DIR, storedPath);
|
|
const uploadRoot = path.resolve(env.UPLOAD_DIR);
|
|
if (!absolute.startsWith(uploadRoot)) {
|
|
throw new ApiError(400, 'Invalid attachment file path');
|
|
}
|
|
return absolute;
|
|
};
|
|
|
|
const unlinkIfExists = (absolutePath) => {
|
|
if (fs.existsSync(absolutePath)) {
|
|
fs.unlinkSync(absolutePath);
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
attachmentInclude,
|
|
sanitizeAttachment,
|
|
resolveFilePath,
|
|
unlinkIfExists,
|
|
};
|