5 changed files with 90 additions and 34 deletions
@ -0,0 +1,47 @@
@@ -0,0 +1,47 @@
|
||||
const _ = require("lodash"); |
||||
const ptr = require("json-pointer"); |
||||
|
||||
function resolvePointer(data, rootPath, relativePath) { |
||||
if (relativePath[0] === "/") return ptr.get(data, relativePath); |
||||
|
||||
const m = relativePath.match(/^(\d+)(.*)/); |
||||
relativePath = m[2]; |
||||
for (let i = 0; i < parseInt(m[1]); i++) { |
||||
rootPath = rootPath.replace(/\/[^\/]+$/, ""); |
||||
} |
||||
|
||||
return ptr.get(data, rootPath + relativePath); |
||||
} |
||||
|
||||
module.exports = (ajv) => |
||||
ajv.addKeyword({ |
||||
keyword: "sumOf", |
||||
validate: function validate( |
||||
{ list, map }, |
||||
total, |
||||
_parent, |
||||
{ rootData, instancePath } |
||||
) { |
||||
if (list.$data) { |
||||
list = resolvePointer(rootData, instancePath, list.$data); |
||||
} |
||||
|
||||
if (map) data = _.map(data, map); |
||||
|
||||
if (_.sum(list) === total) return true; |
||||
|
||||
validate.errors = [ |
||||
{ |
||||
keyword: "sumOf", |
||||
message: "should add up to sum total", |
||||
params: { |
||||
list, |
||||
}, |
||||
}, |
||||
]; |
||||
|
||||
return false; |
||||
}, |
||||
$data: true, |
||||
errors: true, |
||||
}); |
Loading…
Reference in new issue