How to use tv4 - 10 common examples

To help you get started, we’ve selected a few tv4 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 postmanlabs / postman-collection-transformer / tests / schema / example-validity-spec.js View on Github external
it('must be a valid V1 collection: ' + sampleName + '.json', function (done) {
                var validator = tv4.freshApi(),
                    result;
                validator.addSchema(schema);
                // Some of the converter functions assign "undefined" value to some properties,
                // It is necessary to get rid of them (otherwise schema validation sees an "undefined" and fails).
                // Converting to and parsing from JSON does this.
                result = validator.validate(sample, schema);
                if (!result) {
                    console.log(JSON.stringify(validator.error, null, 4)); // Helps debug on CI
                }
                if (validator.missing.length) {
                    console.log(validator.missing);
                    result = false;
                }
                expect(result).to.be(true);
                done();
            });
github postmanlabs / postman-collection-transformer / tests / unit / converter-v2-to-v1-spec.js View on Github external
it('must create a valid V1 collection from ' + sampleName + '.json with synchronous API', function (done) {
                var validator = tv4.freshApi(),
                    result,
                    converted;
                validator.addSchema(schema);
                converted = converter.convert(sample);

                // Some of the converter functions assign "undefined" value to some properties,
                // It is necessary to get rid of them (otherwise schema validation sees an "undefined" and fails).
                // Converting to and parsing from JSON does this.
                converted = JSON.parse(JSON.stringify(converted));

                result = validator.validate(converted, schema);
                if (!result) {
                    console.log(JSON.stringify(validator.error, null, 4)); // Helps debug on CI
                }
                if (validator.missing.length) {
                    console.log(validator.missing);
github mozilla / webmaker-android / test / unit / templates.js View on Github external
var assert = require('assert');
var jsonValidator = require('tv4');
var validate = jsonValidator.validateMultiple;
var templates = require('../../lib/templates.json');

// Localization strings
var localeFile = require('../../locale/en_US/webmaker-app.json');
var localizedStrings = [];
Object.keys(localeFile).forEach(function (localizedStr) {
	localizedStrings.push(localizedStr.toLowerCase());
});

jsonValidator.addFormat('localized', function (data) {
	if(typeof data === 'string' && localizedStrings.indexOf(data.toLowerCase()) !== -1) {
		// No error
		return null;
	}

	return 'must be localized';
});

/*
 * JSON schemas
 */
// Type schemas
var stringSchema = {
	type: 'string'
};
var nonEmptyStringSchema = {
github json-schema-faker / json-schema-faker / tests / schema / validator.js View on Github external
}

  const errors = validator.getLastErrors();

  if (errors || !valid) {
    fail.push(errors.map(e => {
      if (e.code === 'PARENT_SCHEMA_VALIDATION_FAILED') {
        return e.inner.map(x => `[z-schema] ${x.message}`).join('\n');
      }

      return `[z-schema] ${e.message}`;
    }).join('\n') || `[z-schema] Invalid schema ${JSON.stringify(sample)}`);
  }

  // tv4
  const api = tv4.freshApi();

  api.banUnknown = false;
  api.cyclicCheck = false;

  Object.keys(fixed).forEach(k => {
    api.addSchema(k, fixed[k]);
  });

  const result = api.validateResult(sample, clone(schema), api.cyclicCheck, api.banUnknown);

  if (result.missing.length) {
    fail.push(`[tv4] Missing ${result.missing.join(', ')}`);
  }

  if (result.error) {
    fail.push(`[tv4] ${result.error}`);
github mhhf / spore / src / lib / publish.es6 View on Github external
// Compile Contracts
  var compiledContracts = compileContracts( config.working_dir, json.files );
  
  
  // pick the contracts specified in the json
  json.contracts = _.pick( compiledContracts, json.contracts );
  
  // transform json to internal
  delete json.files;
  delete json.ignore;
  
  json.pv = config.version;
  

  var valide = tv4.validate( json, require('../specs/ipfs_' + config.ipfs_version + '.json') );
  if( !valide ) {
    console.log('ERROR'.red + ': Could not create package. Please report this!:\n'+tv4.error.message);
    process.exit();
  }

  var jsonHash = addJsonToIPFS( json );
    
  // TODO - Check if cliet has funds to publish the package
  // web3.eth.estimateGas({
  //   to: address, 
  //   data: 
  // });
  // 
  // Inform the user about the gas price
  if( config.cli )
    console.log('brace yourself, gas will be spend!');
github mhhf / spore / src / lib / publish.es6 View on Github external
var validateJson = function( working_dir, json ) {
    
    var valide = tv4.validate( json, require('../specs/user_'+config.client_version+'.json') );
    if( !valide ) {
      console.log('ERROR'.red +': spore.json is not valide:\n' + tv4.error.message );
      process.exit();
    }
    
    let files = json.files;
    
    // Check if any files are about to be included
    if( files.length == 0 ) 
      throw new Error('Include some files first');
    
    // Check if linked files exists
    files.forEach( ( file ) => {
      let exists = fs.existsSync( working_dir + '/' + file );
      if( !exists ) throw new Error(`File ${file} can't be found in ${working_dir}`);
    });
  }
github pwa-builder / pwabuilder-lib / lib / manifestTools / validationRules / w3cManifestSchema.js View on Github external
module.exports = function (manifestContent, callback) {
  var schemaFile = path.resolve(__dirname, '..', 'assets', 'web-manifest.json');
  var schema = JSON.parse(fs.readFileSync(schemaFile).toString());
  
  var extendedSchemaFile = path.resolve(__dirname, '..', 'assets', 'web-manifest-extended.json');
  var extendedSchema = JSON.parse(fs.readFileSync(extendedSchemaFile).toString());
  
  // merge the extended schema with the standard schema 
  for (var property in extendedSchema.properties) { schema.properties[property] = extendedSchema.properties[property]; }
  for (var definition in extendedSchema.definitions) { schema.definitions[definition] = extendedSchema.definitions[definition]; }
  
  var schemaValidation = tv4.validateMultiple(manifestContent, schema, true, true);
  var validationResults = [];
  schemaValidation.errors.forEach(function (err) {
    var message = err.message;
    if (err.subErrors) {
      message = err.subErrors.reduce(function (previous, current) {
        return previous.message + (previous ? ' ' : '') + current.message + '.';
      });
    }
      
    var member = err.dataPath.split('/').pop();
    if (err.code !== tv4.errorCodes.UNKNOWN_PROPERTY || (member && member.indexOf('_') < 0)) {
      validationResults.push({
        'description': message,
        'platform': validationConstants.platforms.all,
        'level': (err.code === tv4.errorCodes.UNKNOWN_PROPERTY) ? validationConstants.levels.warning : validationConstants.levels.error,
        'member': err.dataPath,
github obniz / obniz / _tools / wsDocGenerator.js View on Github external
//   'display',
  //   'switch',
  //   'ble/central',
  //   'ble/peripheral',
  //   'message',
  //   'debug',
  // ];
  let md = [];

  let param = { formatter, conditions, jsonExample };
  param.defines = {};

  let moduleParams = { name: moduleName, methods: [] };
  for (let methodType of ['request', 'response']) {
    let groupUri = '/' + methodType + '/' + moduleName;
    let groupSchema = tv4.getSchema(groupUri);
    if (!groupSchema) continue;
    let commands = groupSchema.anyOf.map(elm => {
      return elm['$ref'];
    });

    let methodParams = {
      uri: groupUri,
      schema: groupSchema,
      method: methodType,
      commands: [],
    };
    for (let command of commands) {
      let schema = tv4.getSchema(command);
      let basePath = groupSchema.basePath;
      let name = command.split('/').pop();
      let commandParam = {
github kr1sp1n / node-vault / src / index.js View on Github external
client.request = (options = {}) => {
    const valid = tv4.validate(options, requestSchema);
    if (!valid) return Promise.reject(tv4.error);
    let uri = `${client.endpoint}/${client.apiVersion}${client.pathPrefix}${options.path}`;
    // Replace unicode encodings.
    uri = uri.replace(///g, '/');
    options.headers = options.headers || {};
    if (typeof client.token === 'string' && client.token.length) {
      options.headers['X-Vault-Token'] = options.headers['X-Vault-Token'] || client.token;
    }
    options.uri = uri;
    debug(options.method, uri);
    if (options.json) debug(options.json);
    return requestPromise(options).then(client.handleVaultResponse);
  };
github sockethub / sockethub / src / validate.ts View on Github external
function validateActivityStream(msg) {
  // TODO figure out a way to allow for special objects from platforms, without
  // ignoring failed activity stream schema checks
  if (! tv4.validate(msg, SockethubSchemas.ActivityStream)) {
    return tv4.getSchema(`http://sockethub.org/schemas/v0/context/${msg.context}/messages`);
  }
  return true;
}