promise.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. var Ajv = require('ajv')
  2. var HARError = require('./error')
  3. var schemas = require('har-schema')
  4. var ajv
  5. function createAjvInstance () {
  6. var ajv = new Ajv({
  7. allErrors: true
  8. })
  9. ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))
  10. ajv.addSchema(schemas)
  11. return ajv
  12. }
  13. function validate (name, data) {
  14. data = data || {}
  15. // validator config
  16. ajv = ajv || createAjvInstance()
  17. var validate = ajv.getSchema(name + '.json')
  18. return new Promise(function (resolve, reject) {
  19. var valid = validate(data)
  20. !valid ? reject(new HARError(validate.errors)) : resolve(data)
  21. })
  22. }
  23. exports.afterRequest = function (data) {
  24. return validate('afterRequest', data)
  25. }
  26. exports.beforeRequest = function (data) {
  27. return validate('beforeRequest', data)
  28. }
  29. exports.browser = function (data) {
  30. return validate('browser', data)
  31. }
  32. exports.cache = function (data) {
  33. return validate('cache', data)
  34. }
  35. exports.content = function (data) {
  36. return validate('content', data)
  37. }
  38. exports.cookie = function (data) {
  39. return validate('cookie', data)
  40. }
  41. exports.creator = function (data) {
  42. return validate('creator', data)
  43. }
  44. exports.entry = function (data) {
  45. return validate('entry', data)
  46. }
  47. exports.har = function (data) {
  48. return validate('har', data)
  49. }
  50. exports.header = function (data) {
  51. return validate('header', data)
  52. }
  53. exports.log = function (data) {
  54. return validate('log', data)
  55. }
  56. exports.page = function (data) {
  57. return validate('page', data)
  58. }
  59. exports.pageTimings = function (data) {
  60. return validate('pageTimings', data)
  61. }
  62. exports.postData = function (data) {
  63. return validate('postData', data)
  64. }
  65. exports.query = function (data) {
  66. return validate('query', data)
  67. }
  68. exports.request = function (data) {
  69. return validate('request', data)
  70. }
  71. exports.response = function (data) {
  72. return validate('response', data)
  73. }
  74. exports.timings = function (data) {
  75. return validate('timings', data)
  76. }