-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.js
More file actions
64 lines (52 loc) · 1.71 KB
/
Copy pathvalidate.js
File metadata and controls
64 lines (52 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
var Themis = require('themis')
module.exports = function(opts) {
var schema = opts.schema || {}
var validator = Themis.validator(schema);
var basePath = opts.basePath
var id = schema.id || '0'
return {
validate: validate.bind(null, id, basePath, validator)
}
}
function validate(schemaId, basePath, validator, data) {
var report = validator(data, schemaId);
if (! report.valid) {
report.errors = report.errors.map(function(error) {
if (error.validator === 'not') {
error.message += ': '+JSON.stringify(error.validator_value)
}
if (error.code === 'OBJECT_MISSING_REQUIRED_PROPERTY') {
handleMissingRequired(error, report)
}
if (error.code === 'OBJECT_ADDITIONAL_PROPERTIES') {
handleExtraFields(error, report)
}
return {
message: error.message,
absolute_schema_path: ( error.absolute_schema_path || '').replace(/^0#/,basePath +'/schema')
}
})
}
return report
}
function handleMissingRequired(error, report) {
report.missing_fields || (report.missing_fields={})
var match = error.message && error.message.match(/'([^']+)'/)
if (match) {
var field = match[1] || 'unknown_field'
report.missing_fields[field] = (report.missing_fields[field] || 0)+1
}
}
function handleExtraFields(error, report) {
report.blocked_fields || (report.blocked_fields={})
var match = error.message && error.message.match(/(\[[^\]]+\])/)
if (match) {
var fields = tryJson(match[0]) || [ 'unknown_field' ]
fields.forEach(function(field) {
report.blocked_fields[field] = (report.blocked_fields[field] || 0)+1
})
}
function tryJson(str) {
try { return JSON.parse(str) } catch(e) { return str }
}
}