Spaces:
Running
Running
| const path = require('path'); | |
| const { ObjectId } = require('mongodb'); | |
| const { getMediaBucket } = require('../configs/gridfs'); | |
| const { asyncController } = require('../utils/asyncController'); | |
| const EXT_MIME = { | |
| '.webp': 'image/webp', | |
| '.jpg': 'image/jpeg', | |
| '.jpeg': 'image/jpeg', | |
| '.png': 'image/png', | |
| '.gif': 'image/gif', | |
| '.avif': 'image/avif', | |
| }; | |
| const resolveContentType = (file) => { | |
| if (file?.contentType && file.contentType !== 'application/octet-stream') return file.contentType; | |
| if (file?.metadata?.sourceMimeType) return file.metadata.sourceMimeType; | |
| const ext = path.extname(file?.filename || '').toLowerCase(); | |
| return EXT_MIME[ext] || 'application/octet-stream'; | |
| }; | |
| const getMediaById = asyncController(async (req, res) => { | |
| const { id } = req.params; | |
| if (!ObjectId.isValid(id)) { | |
| return res.status(400).json({ message: 'Invalid media id' }); | |
| } | |
| const bucket = getMediaBucket(); | |
| if (!bucket) { | |
| return res.status(503).json({ message: 'Media storage is not ready. Please try again in a moment.' }); | |
| } | |
| // Allow cross-origin embeds so <img> tags load correctly across LAN and different domains. | |
| res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'); | |
| const fileId = new ObjectId(id); | |
| const downloadStream = bucket.openDownloadStream(fileId); | |
| downloadStream.on('file', (file) => { | |
| res.setHeader('Content-Type', resolveContentType(file)); | |
| res.setHeader('Content-Length', String(file.length)); | |
| res.setHeader('Cache-Control', 'public, max-age=2592000, immutable'); | |
| res.setHeader('ETag', `"${String(file._id)}-${file.length}"`); | |
| if (file.uploadDate) { | |
| res.setHeader('Last-Modified', new Date(file.uploadDate).toUTCString()); | |
| } | |
| }); | |
| downloadStream.on('error', () => { | |
| if (!res.headersSent) { | |
| return res.status(404).json({ message: 'Media not found' }); | |
| } | |
| res.destroy(); | |
| }); | |
| downloadStream.pipe(res); | |
| }); | |
| module.exports = { | |
| getMediaById, | |
| }; | |