Last active
July 21, 2023 14:26
-
-
Save webarthur/a187c51edac6964d681694e980bb0b13 to your computer and use it in GitHub Desktop.
Middleware for ExpressJS to validate the request data against a schema using Mongoose.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const Article = require('./article.model.js') | |
const validate = require('./validate.middleware.js') | |
const router = express.Router() | |
router.get('/articles', | |
validate('query', { | |
title: String, | |
text: String, | |
}), | |
(req, res, next) => { | |
Article.find(req.query) | |
.then(result => res.json(result)) | |
.catch(error => next(error)) | |
}) | |
router.patch('/articles/:id', | |
validate('body', { | |
title: String, | |
text: String, | |
}), | |
(req, res, next) => { | |
Article.create(req.body) | |
.then(result => res.json(result)) | |
.catch(error => next(error)) | |
}) | |
module.exports = router |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require('mongoose') | |
/** | |
* Validates the request data against a schema using Mongoose. | |
* @param {string} type - The type of data to validate (e.g., 'body', 'params', 'query'). | |
* @param {object} rawSchema - The raw schema object to validate against. | |
* @param {Object} options - Additional options for validation (default: {}). | |
* @returns {Function} - Middleware function to validate the data. | |
*/ | |
function validate (type, rawSchema) { | |
const schema = new mongoose.Schema(rawSchema, { | |
_id: false, | |
autoCreate: false, | |
versionKey: false, | |
timestamps: false, | |
}) | |
const Model = mongoose.model('validate-' + Date.now(), schema) | |
// Middleware function to validate the request data. | |
return function (req, res, next) { | |
const rawData = req[type] | |
const model = new Model(rawData) | |
const error = model.validateSync() | |
if (error) { | |
res.status(400).json(error) | |
return | |
} | |
// Update request property | |
req[type] = model | |
next() | |
} | |
} | |
module.exports = validate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment