How to use the JSV.JSV.createEnvironment function in jsv

To help you get started, we’ve selected a few jsv examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mozilla / csp-logger / app.js View on Github external
var http = require('http');
var fs = require('fs');
var url = require('url');
var sequelize = require('sequelize');
var JSV = require('JSV').JSV;

var config = JSON.parse(fs.readFileSync('./env.json', {
  encoding: 'utf8'
}));

var schema = JSON.parse(fs.readFileSync('./env.schema.json', {
  encoding: 'utf8'
}));

var configValidationReport = JSV.createEnvironment().validate(config, schema);

// Validate env.json based on env.schema.json
if (configValidationReport.errors.length > 0) {
  console.log('env.json is invalid');
  console.log(configValidationReport.errors);
  process.exit(1);
}

var sequelizeDB = new sequelize(config.dbName, config.dbUsername, config.dbPassword, {
  host: config.dbHost,
  dialect: config.dbDialect, // or 'sqlite', 'postgres', 'mariadb'
  port: config.dbPort
});

// Authenticate and connect to DB
sequelizeDB
github sockethub / sockethub / lib / sockethub / protocol.js View on Github external
if ((typeof platform.schema !== 'object') ||
        (typeof platform.schema.set !== 'object')) {
      resp('platform has to have a schema defined for set operations. cannot validate request');
      return;
    } else if (typeof job.object.objectType !== 'string') {
      resp('this set object has no object.objectType (ie. "credentials"), cannot process.');
      return;
    }

    if ((job.object.objectType === 'credentials') &&
        (typeof platform.schema.set.credentials === 'object') &&
        (typeof platform.schema.set.credentials.properties === 'object')) {

      var JSVlib = require('JSV').JSV; // json schema validator
      var jsv = JSVlib.createEnvironment();
      var report = jsv.validate(job.object, platform.schema.set.credentials.properties);
      if (report.errors.length !== 0) {  // protocol.js json errors
        resp('invalid object format ' + JSON.stringify(report.errors));
        return;
      } else {
        console.debug(' [dispatcher:set] job.object schema validated ');//, report);
      }
    } else {
      resp('unknown objectType for this target platform, cannot process');
    }

    // set the value of object into a redis session DB
    session.getPlatformSession(job.target[0].platform).then(function (psession) {
      console.info(' [dispatcher:set] setting config for platform [' +
                   job.target[0].platform + '] key ['+job.actor.address+']');
      psession.setConfig(job.object.objectType, job.actor.address, job).then(function () {
github racker / gutsy / extern / devopsjson / lib / web / app.js View on Github external
var express = require('express');
var path = require('path');
var JSV = require('JSV').JSV;
var schema = require('./schema').schema;
var middleware = require('./middleware');

var TEMPLATE_DIR = path.join(__dirname, 'views');

// http://tools.ietf.org/html/draft-zyp-json-schema-03
var jsv_env = JSV.createEnvironment('json-schema-draft-03');

exports.run = function(argv) {
  var app = express.createServer();

  app.set('views', TEMPLATE_DIR);
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});

  /* setup middleware */
  app.use(express.bodyParser());
  app.use(middleware.logger());
  app.use('/static', express.static(path.join(__dirname, '..', '..', 'extern')));
  app.use('/static', express.static(path.join(__dirname, '..', '..', 'static')));

  app.get('/', function(req, res) {
    res.render('index.jade', {
github zaach / jsonlint / lib / cli.js View on Github external
function parse (source) {
  var parsed,
      formatted;

  try {
    parsed = options.sort ?
      sortObject(parser.parse(source)) :
      parser.parse(source);

    if (options.validate) {
      var env = JSV.createEnvironment(options.env);
      var schema = JSON.parse(fs.readFileSync(path.normalize(options.validate), "utf8"));
      var report = env.validate(parsed, schema);
      if (report.errors.length) {
        throw report.errors.reduce(schemaError, 'Validation Errors:');
      }
    }

    return JSON.stringify(parsed, null, options.indent);
  } catch (e) {
    if (options.forcePrettyPrint) {
      /* From https://github.com/umbrae/jsonlintdotcom:
       * If we failed to validate, run our manual formatter and then re-validate so that we
       * can get a better line number. On a successful validate, we don't want to run our
       * manual formatter because the automatic one is faster and probably more reliable.
       */
github cainus / mongoJsonSchema / index.js View on Github external
return new Schema(input, options);
  }
  options = options || {};
  // All mongo schemas have ids, but this is not always present (for example, on input)
  input._id = {
    type: "objectid"
  };
  this._schema = {
    type: 'object',
    properties: input,
    additionalProperties: !!options.additionalProperties
  };
  if (options.name) this.name = options.name;
  this._jsonSchema = toJsonSchema(this._schema);
  this._partialJsonSchema = toPartialJsonSchema(this._jsonSchema);
  this.jsonValidator = JSV.createEnvironment().createSchema(this._jsonSchema);
  this.partialJsonValidator = JSV.createEnvironment().createSchema(this._partialJsonSchema);
};
github fhellwig / jsvutil / lib / jsv.js View on Github external
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

//-----------------------------------------------------------------------------
// This module provides an interface to the JSON Schema Validator (JSV).
//-----------------------------------------------------------------------------

var os = require('os');
var util = require('util');
var JSV = require('JSV').JSV;

var env = JSV.createEnvironment();

/**
 * Validates the specified instance against the specified schema.
 */
function validate(instance, schema) {
    var report = env.validate(instance, schema);
    if (report.errors.length > 0) {
        throw error('Schema validation failed.', report.errors);
    }
    return instance;
}

exports.validate = validate;

/**
 * Checks that the specified schema is valid.
github sockethub / sockethub / lib / protocols / dispatcher.js View on Github external
module.exports = (function() {
  var pub = {};
  var _ = {};
  var JSVlib = require('JSV').JSV; // json schema validator
  var jsv = JSVlib.createEnvironment();

  pub.init = function (protoName, connection) {
    _.protoName = protoName;
    _.connection = connection;
    var report;

    // when we get a new connection, and the protocol specified is matched to the
    // list in the config, then this dispatcher is called.
    //
    // first we do basic checking on the protocol.js file to ensure that it's
    // passes basic checks and has the right base-properties.
    try {
      proto = require("./" + protoName + "/protocol.js");
    } catch (e) {
      throw 'unable to load lib/protocols/' + protoName + "/protocol.js " + e;
    }
github sockethub / sockethub / test / 15-platforms-suite.js View on Github external
if (data === undefined) {
        test.result(false, 'unable to load platform module "'+name+'" : '+err);
      } else {
        //test.result(true, 'yoyo2');
        //test.assertTypeAnd(data, 'object', 'test data #'+num+' not an object '+name+' ['+err+']');
        //test.assertTypeAnd(p.schema[prop], 'object', 'platform does not have defined schema property '+prop+' ['+err+']');
        //console.log('DATA: ', data.data);
        //console.log('TYPE: ', type);
        //console.log('PROP: ', prop);
        //console.log('SCHEMA: ', p.schema[type]);
        test.assertTypeAnd(p.schema[type], 'object');
        test.assertTypeAnd(p.schema[type].credentials, 'object');
        test.assertTypeAnd(p.schema[type].credentials.properties, 'object');
        test.assertTypeAnd(p.schema[type].credentials.properties.object, 'object');

        var jsv = JSVlib.createEnvironment();
        var report = jsv.validate(data.data, p.schema[type].credentials.properties.object);
        //console.log('error report: ', report.errors);
        //console.log('error report length: ', report.errors.length);

        if (report.errors.length === 0) {
          test.result(true, 'PASSED!');
        } else {
          test.result(false, 'schema validation failed: '+JSON.stringify(report.errors));
        }
        //test.assert(report.errors.length, 0); //, 'schema validation failed: '+JSON.stringify(report.errors));
      }
    }
  };
github sockethub / sockethub / lib / protocols / handler.js View on Github external
}

  for (var i = 0, len = proto.commands.length; i < len; i = i + 1) {
    if (typeof proto.commands[i].name !== "string") {
      throw 'invalid format in lib/protocols/' + protoName + "/protocol.js\n'name' property must exist and be of type 'string'";
    }
    if (typeof proto.commands[i].schema !== 'object') {
      throw 'invalid format in lib/protocols/' + protoName + "/protocol.js\n'schema' property must exist and be of type 'object'";
    }
    if (typeof proto.commands[i].func !== 'function') {
      throw 'invalid format in lib/protocols/' + protoName + "/protocol.js\n'func' property must exist and be of type 'function'";
    }
  }

  var JSV = require('JSV').JSV;
  var env = JSV.createEnvironment();
  var curry = require('curry');

  connection.on("message", function (message) {
    if (message.type === 'utf8') {
      console.log(' ['+protoName+'] received message: ' + message.utf8Data);

      var msg = false;
      try {
        msg = JSON.parse(message.utf8Data);
      } catch (e) {
        console.log(' [ws] invalid JSON!');
      }

      var report, onError;
      if (typeof msg['command'] === 'string') {
        if (typeof proto.commands[msg['command']] === 'object') {
github racker / gutsy / lib / utils / common.js View on Github external
exports.validate_devops = function(devops){
  var jsv_env = JSV.createEnvironment('json-schema-draft-03');
  var report = jsv_env.validate(devops, schema);

  if (report.errors.length > 0) {
    log.error("ERRORS: ", report.errors);
  }
  return report;
};