/apier-validationsrunner

Runs the request validations. Sync and async.

Primary LanguageJavaScriptMIT LicenseMIT

apier-validationsrunner Build Status

Runs the request validations. Sync and async.
Create an object with the validations and send it to the validationsRunner for execution

var validations = {
	username: {
		EMPTY: req.requestData.username,
		INVALID_LENGTH: function(req, resolve) {
			var username = req.requestData.username;
			if (username && username.length >= 4) {
				resolve(true);
			} else {
				resolve(false);
			}
		}
	},
	password: {
		INVALID_LENGTH: function(req, resolve) {
			var password = req.requestData.password;
			if (password && password.length >= 4) {
				resolve(true);
			} else {
				resolve(false);
			}
		}
	},
	email: {
		INVALID: function(req, resolve) {
			if (req.requestData.email && validator.isEmail(req.requestData.email)) {
				resolve(true);
			} else {
				resolve(false);
			}
		}
	}
};

validationsRunner(req, res, next, validations);

On the example above, we have 4 validations. If the username is empty, the validationsRunner will send a response with the error username.EMPTY.

The validations are executed sequencially, but the functions are executed at the end. Each attribute of the object can either return a truthy/falsy expression or a function.

The expressions are executed first and on first error, a response is sent back to the client.

The functions are executed last, and can be used to include "longer" validations or async validations that need to communicate with the database. Functions use the req, and resolve params. Use resolve(true) or resolve(false) to define the validation result. False means error.

Installation

Download node at nodejs.org and install it, if you haven't already.

npm install apier-validationsrunner --save

Dependencies

  • apier-responsebuilder: Builds and sends the response of apier.
  • es6-promise: A lightweight library that provides tools for organizing asynchronous code
  • lodash: Lodash modular utilities.
  • reqlog: A simple Node.js logger. Very closely attached to a request.

Dev Dependencies

License

MIT

Generated by package-json-to-readme