Skip to content

Instantly share code, notes, and snippets.

@smebberson
Last active May 3, 2017 00:01
Show Gist options
  • Save smebberson/c11850c067f2bc519f657a1154f93dea to your computer and use it in GitHub Desktop.
Save smebberson/c11850c067f2bc519f657a1154f93dea to your computer and use it in GitHub Desktop.
Example validation rules
'use strict';
/**
* Member Api schema.
* @return {Object} Mongoose model object.
*/
const memberApiSchema = () => {
const schema = new mongoose.Schema({
active: { type: String, required: true, enum: ['true', 'false'] },
capmemberid: { type: String, required: true },
capmembername: { type: String, required: true },
capmembernumber: { type: String, required: true },
country: { type: String, required: true },
email: { type: String, required: true },
fax: { type: String },
phone: { type: String },
postcode: { type: String },
state: { type: String },
street: { type: String, required: true },
suburb: { type: String }
});
return mongoose.model('MemberApi', schema);
};
/**
* User Api schema.
* @return {Object} Mongoose model object.
*/
const userApiSchema = () => {
const schema = new mongoose.Schema({
active: { type: String, required: true, enum: ['true', 'false'] },
email: { type: String, required: true },
member: { type: String },
phone: { type: String },
username: { type: String, required: true }
});
return mongoose.model('UserApi', schema);
}
/**
* Validate an Api request for the correct fields.
* @param {Object} Model Mongoose model.
* @return {Void} Calls the middleware function.
*/
const validate = (Model) => {
const middleware = (req, res, next) => {
const { body } = req;
// We can skip all this if there is no body.
if (!body || !Object.keys(body).length) {
return next(new HttpError(400, {
code: 'ApiValidation',
message: 'No request body was provided'
}));
}
const data = [].concat(body);
// Some defaults.
let errorCode = 'ApiValidation';
let errorMessage = 'Api validation failed';
let errors = [];
data.forEach((item) => {
// Convert all properties and values to lowercase.
const parsedItem = {};
Object.keys(item).map((prop) => {
let value = item[prop];
// Value might not be a string.
if (typeof value === 'string') {
value = value.toLowerCase();
}
parsedItem[prop.toLowerCase()] = value;
});
const err = new Model(parsedItem).validateSync();
if (err) {
errors.push(err);
}
});
if (errors) {
const error = new HttpError(400, {
code: errorCode,
message: errorMessage,
details: errors
});
return next(error);
}
return next();
};
return middleware;
}
module.exports = {
schemas: {
member: memberApiSchema(),
user: userApiSchema()
},
validate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment