opt-cc/server/middleware/validators.js

39 lines
1.0 KiB
JavaScript
Raw Permalink Normal View History

2018-03-12 09:26:44 +01:00
'use strict';
// HTTP status codes by name
const codes = require('../routes/http-codes');
// library to check image dimensions from file buffer
const sizeOf = require('buffer-image-size');
/**
* check if id has valid UUID format
*
* @param {object} req
* @param {function} res
* @param {function} next
* @return {boolean}
*/
const idValidator = (req, res, next) => {
const reqId = req.params.id;
if (!reqId.match(/^[0-9a-fA-F]{24}$/)) {
2018-03-12 09:26:44 +01:00
const err = new Error('Invalid request id format');
err.status = codes.notfound;
return next(err);
}
next();
};
const imageDimensionValidator = (imageFileBuf, maxWidth, maxHeight) => {
const dimensions = sizeOf(imageFileBuf);
if (dimensions.width > maxWidth || dimensions.height > maxHeight) {
let err = new Error(`Image exceeds maximum dimensions of ${maxWidth}px width and ${maxHeight}px height`);
err.status = codes.wrongrequest;
return err;
}
};
exports.idValidator = idValidator;
exports.imageDimensionValidator = imageDimensionValidator;