Spaces:
Running
Running
File size: 6,652 Bytes
e8c33fa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | const path = require('path');
const { Readable } = require('stream');
const { pipeline } = require('stream/promises');
const Document = require('../models/Document');
const { getDocumentsBucket } = require('../configs/gridfs');
const { ensureValidIdOrRespond, findByIdOrRespondNotFound } = require('../utils/controllerResponses');
const { asyncController } = require('../utils/asyncController');
const parseBoundedInt = (value, { min, max, fallback }) => {
const parsed = Number.parseInt(String(value ?? ''), 10);
if (!Number.isInteger(parsed)) return fallback;
return Math.min(Math.max(parsed, min), max);
};
const sanitizeDownloadFilename = (filename) => {
const normalized = String(filename || 'document')
.replace(/[\r\n"]/g, '')
.trim();
return normalized || 'document';
};
const sanitizeBaseName = (name) =>
name
.trim()
.replace(/[^a-zA-Z0-9._-]+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.toLowerCase();
const buildStoredFilename = (originalName) => {
const ext = path.extname(originalName || '').toLowerCase();
const base = path.basename(originalName || 'document', ext);
const safeBase = sanitizeBaseName(base) || 'document';
return `${Date.now()}-${Math.round(Math.random() * 1e9)}-${safeBase}${ext}`;
};
const toClientDocument = (doc) => ({
_id: doc._id,
originalName: doc.originalName,
mimeType: doc.mimeType,
size: doc.size,
category: doc.category,
description: doc.description,
uploadedBy: doc.uploadedBy ?? null,
createdAt: doc.createdAt,
updatedAt: doc.updatedAt,
downloadUrl: `/api/documents/${doc._id}/download`,
});
const requireDocumentsBucket = () => {
const bucket = getDocumentsBucket();
if (!bucket) {
const err = new Error('GridFS is not ready. Please try again in a moment.');
err.statusCode = 503;
throw err;
}
return bucket;
};
const listDocuments = asyncController(async (req, res) => {
const hasPaginationQuery = req.query.page !== undefined || req.query.pageSize !== undefined;
const legacyLimit = parseBoundedInt(req.query.limit, { min: 1, max: 1000, fallback: 300 });
const page = parseBoundedInt(req.query.page, { min: 1, max: 5000, fallback: 1 });
const pageSize = parseBoundedInt(req.query.pageSize, { min: 1, max: 100, fallback: 25 });
const category = String(req.query.category || '').trim();
const query = category ? { category } : {};
if (!hasPaginationQuery) {
const docs = await Document.find(query)
.sort({ createdAt: -1 })
.limit(legacyLimit)
.lean();
res.json(docs.map(toClientDocument));
return;
}
const skip = (page - 1) * pageSize;
const [total, docs] = await Promise.all([
Document.countDocuments(query),
Document.find(query)
.sort({ createdAt: -1 })
.skip(skip)
.limit(pageSize)
.lean(),
]);
res.json({
items: docs.map(toClientDocument),
total,
page,
pageSize,
totalPages: Math.max(1, Math.ceil(total / pageSize)),
});
});
const getDocumentById = asyncController(async (req, res) => {
if (!ensureValidIdOrRespond(res, req.params.id, 'document')) return;
const doc = await findByIdOrRespondNotFound({
Model: Document,
id: req.params.id,
res,
notFoundMessage: 'Document not found',
lean: true,
});
if (!doc) return;
res.json(toClientDocument(doc));
});
const downloadDocument = asyncController(async (req, res) => {
if (!ensureValidIdOrRespond(res, req.params.id, 'document')) return;
const doc = await findByIdOrRespondNotFound({
Model: Document,
id: req.params.id,
res,
notFoundMessage: 'Document not found',
lean: true,
});
if (!doc) return;
const bucket = requireDocumentsBucket();
const downloadStream = bucket.openDownloadStream(doc.fileId);
const safeName = sanitizeDownloadFilename(doc.originalName);
const isInline = req.query.inline === 'true' || req.query.inline === '1';
res.setHeader('Content-Type', doc.mimeType || 'application/octet-stream');
res.setHeader('Content-Disposition', `${isInline ? 'inline' : 'attachment'}; filename="${safeName}"`);
res.setHeader('Cache-Control', 'private, max-age=60');
if (typeof doc.size === 'number' && doc.size >= 0) {
res.setHeader('Content-Length', String(doc.size));
}
downloadStream.on('error', () => {
if (!res.headersSent) {
return res.status(404).json({ message: 'Stored file not found' });
}
res.destroy();
});
downloadStream.pipe(res);
});
const uploadDocument = asyncController(async (req, res) => {
if (!req.file || !req.file.buffer) {
return res.status(400).json({ message: 'No document file uploaded' });
}
const category = String(req.body.category || 'general').trim() || 'general';
const description = String(req.body.description || '').trim();
const bucket = requireDocumentsBucket();
const storedFilename = buildStoredFilename(req.file.originalname);
const uploadStream = bucket.openUploadStream(storedFilename, {
contentType: req.file.mimetype || 'application/octet-stream',
metadata: { originalName: req.file.originalname, category },
});
const uploadedFileId = uploadStream.id;
try {
await pipeline(Readable.from(req.file.buffer), uploadStream);
} catch (err) {
try {
const b = getDocumentsBucket();
if (b) await b.delete(uploadedFileId);
} catch (_) {
// Best-effort cleanup to avoid orphaned files.
}
throw err;
}
const doc = await Document.create({
fileId: uploadStream.id,
filename: storedFilename,
originalName: req.file.originalname,
mimeType: req.file.mimetype || 'application/octet-stream',
size: req.file.size,
category,
description,
uploadedBy: req.user?.id || req.user?._id || null,
});
res.status(201).json(toClientDocument(doc.toObject()));
}, { defaultStatus: 400 });
const deleteDocument = asyncController(async (req, res) => {
if (!ensureValidIdOrRespond(res, req.params.id, 'document')) return;
const doc = await findByIdOrRespondNotFound({
Model: Document,
id: req.params.id,
res,
notFoundMessage: 'Document not found',
});
if (!doc) return;
const bucket = requireDocumentsBucket();
try {
await bucket.delete(doc.fileId);
} catch (err) {
// Ignore missing file in GridFS but preserve other errors.
if (err?.codeName !== 'NamespaceNotFound' && !String(err.message || '').includes('FileNotFound')) {
throw err;
}
}
await doc.deleteOne();
res.json({ message: 'Document removed' });
});
module.exports = {
listDocuments,
getDocumentById,
downloadDocument,
uploadDocument,
deleteDocument,
};
|