@nodeswork/sbase
Version:
Basic REST api foundation from Nodeswork.
65 lines (63 loc) • 2.16 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("underscore");
const validators = require("./validators");
const utils_1 = require("@nodeswork/utils");
const object_path_1 = require("object-path");
function params(options) {
const mappedOptions = _.map(options, (v, key) => {
const vs = _.chain([v])
.flatten()
.filter(x => !!x)
.value();
if (key.startsWith('!')) {
vs.push(validators.required);
key = key.substring(1);
}
return { key, validators: vs };
});
return async (ctx, next) => {
ctx.errors = processValidators(ctx.request, mappedOptions, ctx);
if (!_.isEmpty(ctx.errors)) {
throw utils_1.NodesworkError.unprocessableEntity(undefined, {
errors: ctx.errors,
});
}
else {
await next();
}
};
}
exports.params = params;
function processValidators(target, standardOptions, root) {
const errors = [];
for (const o of standardOptions) {
const newTarget = o.key.startsWith('~') ? root : target;
const key = o.key.startsWith('~') ? o.key.substring(1) : o.key;
for (const fn of o.validators) {
const value = object_path_1.withInheritedProps.get(newTarget, key);
const pass = fn(newTarget, key, value, root);
if (pass === false || _.isString(pass)) {
errors.push({
path: o.key,
value,
failed: fn.name,
reason: pass || '',
});
}
if (_.isArray(pass)) {
for (const error of pass) {
errors.push({
path: o.key + '.' + error.path,
value: error.value,
failed: fn.name + '>' + error.failed,
reason: error.reason,
});
}
}
}
}
return errors;
}
exports.processValidators = processValidators;
//# sourceMappingURL=params.js.map