koa-middle-validator
Advanced tools
Comparing version 1.0.0 to 1.1.0
@@ -1,2 +0,2 @@ | ||
var co = require('co') | ||
var co = require('co'); | ||
var validator = require('validator'); | ||
@@ -20,9 +20,9 @@ var _ = require('lodash'); | ||
for (var name in validator) { | ||
if (typeof validator[name] !== 'function' || name === 'toString' || | ||
name === 'toDate' || name === 'extend' || name === 'init' || | ||
name === 'isServerSide') { | ||
if (typeof validator[name] !== 'function' || name === 'toString' || | ||
name === 'toDate' || name === 'extend' || name === 'init' || | ||
name === 'isServerSide') { | ||
continue; | ||
} | ||
validator.extend(name, validator[name]); | ||
} | ||
validator.extend(name, validator[name]); | ||
} | ||
}; | ||
@@ -69,3 +69,3 @@ | ||
this.value = undefined; | ||
if (location && ['body','query'].includes(location)) { | ||
if (location && ['body', 'query'].includes(location)) { | ||
this.value = _.get(ctx.request[location], param); | ||
@@ -80,2 +80,5 @@ } else { | ||
this.lastError = null; // used by withMessage to get the values of the last error | ||
// set legal result | ||
this.ctx._validationLegalResult[this.param] = this.value; | ||
return this; | ||
@@ -106,5 +109,6 @@ } | ||
this.ctx = ctx.request; | ||
this.ctx = ctx; | ||
this.param = param; | ||
this.locations = locations; | ||
return this; | ||
@@ -183,20 +187,20 @@ } | ||
if (this.lastError) { | ||
if (this.lastError.isAsync) { | ||
this.ctx._asyncValidationErrors.pop().catch(function() { | ||
// Suppress errors from original promise - they should go to the new one. | ||
// Otherwise bluebird throws an 'unhandled rejection' error | ||
}); | ||
var error = formatErrors.call(this.lastError.context, this.lastError.param, message, this.lastError.value); | ||
var promise = this.lastError.promise.catch(function() { | ||
return Promise.reject(error); | ||
}); | ||
this.ctx._asyncValidationErrors.push(promise); | ||
} else { | ||
this.validationErrors.pop(); | ||
this.ctx._validationErrors.pop(); | ||
var errorMessage = formatErrors.call(this, this.lastError.param, message, this.lastError.value); | ||
this.validationErrors.push(errorMessage); | ||
this.ctx._validationErrors.push(errorMessage); | ||
this.lastError = null; | ||
} | ||
if (this.lastError.isAsync) { | ||
this.ctx._asyncValidationErrors.pop().catch(function() { | ||
// Suppress errors from original promise - they should go to the new one. | ||
// Otherwise bluebird throws an 'unhandled rejection' error | ||
}); | ||
var error = formatErrors.call(this.lastError.context, this.lastError.param, message, this.lastError.value); | ||
var promise = this.lastError.promise.catch(function() { | ||
return Promise.reject(error); | ||
}); | ||
this.ctx._asyncValidationErrors.push(promise); | ||
} else { | ||
this.validationErrors.pop(); | ||
this.ctx._validationErrors.pop(); | ||
var errorMessage = formatErrors.call(this, this.lastError.param, message, this.lastError.value); | ||
this.validationErrors.push(errorMessage); | ||
this.ctx._validationErrors.push(errorMessage); | ||
this.lastError = null; | ||
} | ||
} | ||
@@ -214,3 +218,3 @@ return this; | ||
return co.wrap(function *(ctx, next) { | ||
return co.wrap(function*(ctx, next) { | ||
var locations = ['body', 'params', 'query']; | ||
@@ -220,2 +224,5 @@ | ||
ctx._asyncValidationErrors = []; | ||
ctx._validationLegalResult = {}; | ||
ctx._sanitizerLegalResult = {}; | ||
ctx.validationErrors = function(mapped, promisesResolved) { | ||
@@ -264,3 +271,3 @@ if (!promisesResolved && ctx._asyncValidationErrors.length > 0) { | ||
ctx.getValidationResult = function() { | ||
ctx.getValidationResult = function(mapped) { | ||
return new Promise(function(resolve) { | ||
@@ -287,2 +294,22 @@ var promises = ctx._asyncValidationErrors; | ||
ctx.getValidationLegalResult = function(mapped) { | ||
return new Promise(function(resolve, reject) { | ||
var promises = ctx._asyncValidationErrors; | ||
Promise.all(promises.map(function(promise) { | ||
return Promise.resolve(promise).reflect(); | ||
})).then(function(results) { | ||
results.forEach(function(result) { | ||
if (result.isRejected()) { | ||
ctx._validationErrors.push(result.reason()); | ||
} | ||
}); | ||
if (ctx._validationErrors.length > 0) { | ||
return reject(ctx.validationErrors(mapped, true)); | ||
} | ||
resolve(ctx._validationLegalResult); | ||
}); | ||
}) | ||
} | ||
locations.forEach(function(location) { | ||
@@ -315,2 +342,6 @@ ctx['sanitize' + _.capitalize(location)] = function(param) { | ||
ctx.getSanitizerLegalResult = function() { | ||
return Promise.resolve(ctx._sanitizerLegalResult); | ||
}; | ||
// ctx.checkFiles = function(param, failMsg) { | ||
@@ -459,3 +490,5 @@ // return new ValidatorChain(param, failMsg, ctx, 'files', options); | ||
if (typeof msg === 'string') { | ||
args.forEach(function(arg, i) { msg = msg.replace('%' + i, arg); }); | ||
args.forEach(function(arg, i) { | ||
msg = msg.replace('%' + i, arg); | ||
}); | ||
} | ||
@@ -479,3 +512,7 @@ var error = formatErrors.call(this, this.param, msg || 'Invalid value', this.value); | ||
this.ctx._validationErrors.push(error); | ||
this.lastError = { param: this.param, value: this.value, isAsync: false }; | ||
this.lastError = { | ||
param: this.param, | ||
value: this.value, | ||
isAsync: false | ||
}; | ||
} else { | ||
@@ -507,4 +544,8 @@ this.lastError = null; | ||
result = container[methodName].apply(container, args); | ||
// set the result after sanitize in ctx | ||
_.set(this.ctx.request[this.locations[i]], this.param, result); | ||
_.set(this.ctx[this.locations[i]], this.param, result); | ||
// set legal result | ||
_.set(this.ctx._sanitizerLegalResult, this.param, result); | ||
this.values[i] = result; | ||
@@ -534,3 +575,3 @@ } | ||
return 'body'; | ||
} | ||
} | ||
// else if (_.has(ctx.headers, name)) { | ||
@@ -537,0 +578,0 @@ // return 'headers'; |
@@ -6,3 +6,3 @@ { | ||
"homepage": "https://github.com/luckcoding/koa-middle-validator", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"main": "./index.js", | ||
@@ -9,0 +9,0 @@ "scripts": { |
@@ -185,5 +185,6 @@ # koa-middle-validator | ||
### Result API | ||
The method `ctx.getValidationResult()` returns a Promise which resolves to a result object. | ||
### getValidationResult | ||
Runs all validations and returns a validation result object for the errors gathered, for both sync and async validators. | ||
```js | ||
@@ -196,5 +197,26 @@ ctx.assert('email', 'required').notEmpty(); | ||
// do something with the validation result | ||
if (!errors.isEmpty()) { | ||
ctx.body = errors.array(); | ||
} else { | ||
// ctx.body = {}; | ||
} | ||
}); | ||
``` | ||
### getValidationLegalResult (v1.1.0) | ||
Runs all validations and return the validated values; | ||
```js | ||
try { | ||
ctx.checkBody({}) | ||
const values = await ctx.getValidationLegalResult() | ||
mongoose.model.save(values) | ||
} catch (e) { | ||
// $$emit error | ||
} | ||
``` | ||
## Optional input | ||
@@ -240,2 +262,19 @@ | ||
~~Only sanitizes `ctx.cookies`. This method is not covered by the general `ctx.sanitize()`.~~ | ||
## Sanitizer result | ||
### getSanitizerLegalResult (v1.1.0) | ||
Runs all sanitizer and return the sanitized values; | ||
```js | ||
try { | ||
ctx.sanitizeQuery('page').toInt() | ||
const values = await ctx.getSanitizerLegalResult() | ||
mongoose.model.save(values) | ||
} catch (e) { | ||
// $$emit error | ||
} | ||
``` |
135123
44
2933
277