| 1 | var Ajv = require('ajv') |
| 2 | var HARError = require('./error') |
| 3 | var schemas = require('har-schema') |
| 4 | |
| 5 | var ajv |
| 6 | |
| 7 | function validate (name, data, next) { |
| 8 | data = data || {} |
| 9 | |
| 10 | // validator config |
| 11 | ajv = ajv || new Ajv({ |
| 12 | allErrors: true, |
| 13 | schemas: schemas |
| 14 | }) |
| 15 | |
| 16 | var validate = ajv.getSchema(name + '.json') |
| 17 | |
| 18 | var valid = validate(data) |
| 19 | |
| 20 | // callback? |
| 21 | if (typeof next === 'function') { |
| 22 | return next(!valid ? new HARError(validate.errors) : null, valid) |
| 23 | } |
| 24 | |
| 25 | return valid |
| 26 | } |
| 27 | |
| 28 | exports.afterRequest = function (data, next) { |
| 29 | return validate('afterRequest', data, next) |
| 30 | } |
| 31 | |
| 32 | exports.beforeRequest = function (data, next) { |
| 33 | return validate('beforeRequest', data, next) |
| 34 | } |
| 35 | |
| 36 | exports.browser = function (data, next) { |
| 37 | return validate('browser', data, next) |
| 38 | } |
| 39 | |
| 40 | exports.cache = function (data, next) { |
| 41 | return validate('cache', data, next) |
| 42 | } |
| 43 | |
| 44 | exports.content = function (data, next) { |
| 45 | return validate('content', data, next) |
| 46 | } |
| 47 | |
| 48 | exports.cookie = function (data, next) { |
| 49 | return validate('cookie', data, next) |
| 50 | } |
| 51 | |
| 52 | exports.creator = function (data, next) { |
| 53 | return validate('creator', data, next) |
| 54 | } |
| 55 | |
| 56 | exports.entry = function (data, next) { |
| 57 | return validate('entry', data, next) |
| 58 | } |
| 59 | |
| 60 | exports.har = function (data, next) { |
| 61 | return validate('har', data, next) |
| 62 | } |
| 63 | |
| 64 | exports.header = function (data, next) { |
| 65 | return validate('header', data, next) |
| 66 | } |
| 67 | |
| 68 | exports.log = function (data, next) { |
| 69 | return validate('log', data, next) |
| 70 | } |
| 71 | |
| 72 | exports.page = function (data, next) { |
| 73 | return validate('page', data, next) |
| 74 | } |
| 75 | |
| 76 | exports.pageTimings = function (data, next) { |
| 77 | return validate('pageTimings', data, next) |
| 78 | } |
| 79 | |
| 80 | exports.postData = function (data, next) { |
| 81 | return validate('postData', data, next) |
| 82 | } |
| 83 | |
| 84 | exports.query = function (data, next) { |
| 85 | return validate('query', data, next) |
| 86 | } |
| 87 | |
| 88 | exports.request = function (data, next) { |
| 89 | return validate('request', data, next) |
| 90 | } |
| 91 | |
| 92 | exports.response = function (data, next) { |
| 93 | return validate('response', data, next) |
| 94 | } |
| 95 | |
| 96 | exports.timings = function (data, next) { |
| 97 | return validate('timings', data, next) |
| 98 | } |