'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _ajv = require('ajv');

var _ajv2 = _interopRequireDefault(_ajv);

var _ajvErrors = require('ajv-errors');

var _ajvErrors2 = _interopRequireDefault(_ajvErrors);

var _nodeBits = require('node-bits');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var ValidateSubscriber = function () {
  function ValidateSubscriber(config) {
    _classCallCheck(this, ValidateSubscriber);

    this.modelConfig = config.models;

    this.ajv = new _ajv2.default({ allErrors: true, jsonPointers: true });
    (0, _ajvErrors2.default)(this.ajv);
  }

  _createClass(ValidateSubscriber, [{
    key: 'subscribe',
    value: function subscribe() {
      return true;
    }
  }, {
    key: 'perform',
    value: function perform(args) {
      var req = args.req,
          res = args.res,
          name = args.name,
          stage = args.stage,
          verb = args.verb,
          resultSent = args.resultSent;


      if (![_nodeBits.POST, _nodeBits.PUT].includes(verb) || stage !== _nodeBits.BEFORE || resultSent) {
        return false;
      }

      var modelConfig = _lodash2.default.find(this.modelConfig, function (c) {
        return c.model === name;
      });
      if (!modelConfig || !modelConfig.validate) {
        return false;
      }

      var validate = this.ajv.compile(modelConfig.validate);
      if (!validate(req.body)) {
        res.status(500).json(validate.errors);
        args.failure = true;
        return true;
      }

      return false;
    }
  }]);

  return ValidateSubscriber;
}();

exports.default = ValidateSubscriber;