Ghost/core/server/web/api/middleware/upload.js
Hannah Wolfe 36b42505ea Moved upload mw into api app
- Moved upload mw from shared to api as it is not shared (except within the API)
- This file is only used in one part of the app, this updates the code structure to reflect this
- This is one of many similar changes needed to make it easier to refactor to the existing setup
2020-04-22 07:12:25 +01:00

44 lines
1.3 KiB
JavaScript

const config = require('../../../config');
const os = require('os');
const multer = require('multer');
const fs = require('fs-extra');
const {logging} = require('../../../lib/common');
const upload = {
enabledClear: config.get('uploadClear') || true,
multer: multer({dest: os.tmpdir()})
};
const deleteSingleFile = file => fs.unlink(file.path).catch(err => logging.error(err));
const single = name => (req, res, next) => {
const singleUpload = upload.multer.single(name);
singleUpload(req, res, (err) => {
if (err) {
return next(err);
}
if (upload.enabledClear) {
const deleteFiles = () => {
res.removeListener('finish', deleteFiles);
res.removeListener('close', deleteFiles);
if (!req.disableUploadClear) {
if (req.files) {
return req.files.forEach(deleteSingleFile);
}
if (req.file) {
return deleteSingleFile(req.file);
}
}
};
if (!req.disableUploadClear) {
res.on('finish', deleteFiles);
res.on('close', deleteFiles);
}
}
next();
});
};
module.exports = {single};