Files
filing-cabinet-api/middleware/strict_input.js
T

28 lines
980 B
JavaScript

const fs = require('fs');
function strictInput({ body = [], query = [], cleanupUploadedFile = false } = {}) {
const allowedBody = new Set(body);
const allowedQuery = new Set(query);
return function validateInputShape(req, res, next) {
const bodyKeys = Object.keys(req.body || {});
const queryKeys = Object.keys(req.query || {});
const unexpectedBody = bodyKeys.filter((key) => !allowedBody.has(key));
const unexpectedQuery = queryKeys.filter((key) => !allowedQuery.has(key));
if (unexpectedBody.length > 0 || unexpectedQuery.length > 0) {
if (cleanupUploadedFile && req.file?.path) {
fs.promises.unlink(req.file.path).catch(() => {});
}
return res.status(400).json({
error: 'Unexpected request field(s)',
fields: [...unexpectedBody, ...unexpectedQuery],
});
}
next();
};
}
module.exports = { strictInput };