How to use ajv - 10 common examples

To help you get started, we’ve selected a few ajv 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 gajus / surgeon / src / assertions / assertValidDenormalizedQuery.js View on Github external
// @flow

import Ajv from 'ajv';
import denormalizedQueryShema from '../schemas/denormalizedQueryShema.json';
import {
  SurgeonError
} from '../errors';
import type {
  DenormalizedQueryType
} from '../types';

const ajv = new Ajv();

const validate = ajv.compile(denormalizedQueryShema);

export default (denormalizedQuery: DenormalizedQueryType, log: boolean = true): void => {
  if (!validate(denormalizedQuery)) {
    if (log) {
      // eslint-disable-next-line
      console.log('query', denormalizedQuery);

      // eslint-disable-next-line
      console.error('Validation errors', validate.errors);
    }

    throw new SurgeonError('Invalid query.');
  }
};
github stoplightio / spectral / src / functions / schema.ts View on Github external
log: console.log,
  error: console.error,
};

const ajv = new AJV({
  meta: false,
  schemaId: 'auto',
  jsonPointers: true,
  unknownFormats: 'ignore',
  logger,
});
ajv.addMetaSchema(jsonSpecv4);
ajv.addMetaSchema(jsonSpecv6);
ajv.addMetaSchema(jsonSpecv7);
// @ts-ignore
ajv._opts.defaultMeta = jsonSpecv4.id;
// @ts-ignore
ajv._refs['http://json-schema.org/schema'] = 'http://json-schema.org/draft-04/schema';

ajv.addFormat('int32', { type: 'number', validate: oasFormatValidator.int32 });
ajv.addFormat('int64', { type: 'number', validate: oasFormatValidator.int64 });
ajv.addFormat('float', { type: 'number', validate: oasFormatValidator.float });
ajv.addFormat('double', { type: 'number', validate: oasFormatValidator.double });
ajv.addFormat('byte', { type: 'string', validate: oasFormatValidator.byte });

function getSchemaId(schemaObj: JSONSchema): void | string {
  if ('$id' in schemaObj) {
    return schemaObj.$id;
  }

  if ('id' in schemaObj) {
    return schemaObj.id;
github Discord-Bot-Maker-Mods / DBM-Mods / node_modules / har-validator / src / async.js View on Github external
export function validate (name, data = {}, next) {
  // validator config
  ajv = ajv || new Ajv({
    allErrors: true,
    schemas: schemas
  })

  let validate = ajv.getSchema(name + '.json')

  let valid = validate(data)

  // callback?
  if (typeof next === 'function') {
    return next(!valid ? new HARError(validate.errors) : null, valid)
  }

  return valid
}
github opporty-com / Plasma-Cash / backend / app / lib / validate.js View on Github external
'use strict';

import Ajv  from 'ajv';
import fs   from 'fs';
import path  from 'path';

const AJV_OPTIONS = {
  removeAdditional: true,
  coerceTypes: true,
  useDefaults: true,
  allErrors: true,
  errorDataPath: 'property',
  jsonPointers: true // ajv-errors required
};
const ajv = new Ajv(AJV_OPTIONS);

export function validateRequestBySchema (schemaPath, data) {
  return new Promise((resolve, reject) => {
    let schema;
    if (fs.existsSync(path.join(__dirname, schemaPath))) {
      schema = require(schemaPath);
    }  else {
      throw new Error(`schema ${schemaPath} not found`);
    }

    let valid = {errors:[]};

    let validate = ajv.compile(schema);
    if (!validate(data)) {
      valid.errors = validate.errors;
    }
github ditojs / dito / packages / server / src / schema / keywords / _validate.js View on Github external
async validate(func, ...args) {
    // The validator's `ctx` as passed to Ajv with passContext as `this`:
    const params = getParams(this, ...args)
    let result
    try {
      result = (await func(params)) ?? true
    } catch (error) {
      // Async validate methods need to throw their errors.
      throw new Ajv.ValidationError(getErrors(error, params))
    }
    return result
  }
}
github Open-EO / openeo-earthengine-driver / src / processgraph / jsonschema.js View on Github external
_validateGeoJson(data) {
		if (typeof data.type !== 'string') { // ToDo: Fully check against GeoJSON schema
			throw new ajv.ValidationError([{
				message: "Invalid GeoJSON specified (no type property)."
			}]);
		}
		return true;
	}
github Zooz / express-ajv-swagger-validation / src / customKeywords / files.js View on Github external
validate: function filesValidation(schema, data) {
        filesValidation.errors = [];
        const dataFileName = data.map((element) => { return element[fileNameField] });
        let missingFiles = missingElements(dataFileName, schema.required);
        if (missingFiles.length > 0) {
            filesValidation.errors.push(new Ajv.ValidationError({
                keyword: 'files',
                message: `Missing required files: ${missingFiles.toString()}`,
                params: { requiredFiles: schema.required, missingFiles: missingFiles }
            }));
            return false;
        }

        // Check that only the optional files exists
        let allFiles = schema.required.concat(schema.optional);
        let extraFiles = missingElements(allFiles, dataFileName);
        if (extraFiles.length > 0) {
            filesValidation.errors.push(new Ajv.ValidationError({
                keyword: 'files',
                message: `Extra files are not allowed. Not allowed files: ${extraFiles}`,
                params: { allowedFiles: allFiles, extraFiles: extraFiles }
            }));
github ditojs / dito / packages / server / src / app / Validator.js View on Github external
: function(data) {
          // Emulate `options.throw == true` behavior for sync validation:
          // Return `true` if successful, throw `Ajv.ValidationError` otherwise.
          // Use `call()` to pass `this` as context to Ajv, see passContext:
          const result = validator.call(this, data)
          if (!result) {
            throw new Ajv.ValidationError(validator.errors)
          }
          return result
        }
  }
github jupyter-widgets / ipywidgets / jupyter-widgets-htmlmanager / src / embed-webpack.ts View on Github external
// Load json schema validator
var Ajv = require('ajv');
var widget_state_schema = require('jupyter-widgets-schema').v2.state;
var widget_view_schema = require('jupyter-widgets-schema').v2.view;

// BEGIN: Ajv config for json-schema draft 4, from https://github.com/epoberezkin/ajv/releases/tag/5.0.0
// This can be deleted when the schema is moved to draft 6
var ajv = new Ajv({
  meta: false, // optional, to prevent adding draft-06 meta-schema
  extendRefs: true, // optional, current default is to 'fail', spec behaviour is to 'ignore'
  unknownFormats: 'ignore',  // optional, current default is true (fail)
  // ...
});

var metaSchema = require('ajv/lib/refs/json-schema-draft-04.json');
ajv.addMetaSchema(metaSchema);
ajv._opts.defaultMeta = metaSchema.id;

// optional, using unversioned URI is out of spec, see https://github.com/json-schema-org/json-schema-spec/issues/216
ajv._refs['http://json-schema.org/schema'] = 'http://json-schema.org/draft-04/schema';

// Optionally you can also disable keywords defined in draft-06
ajv.removeKeyword('propertyNames');
ajv.removeKeyword('contains');
ajv.removeKeyword('const');
// END: Ajv config for json-schema draft 4, from https://github.com/epoberezkin/ajv/releases/tag/5.0.0

let model_validate = ajv.compile(widget_state_schema);
let view_validate = ajv.compile(widget_view_schema);


// `LoadInlineWidget` is the main function called on load of the web page.
github vcync / modV / src / store / modules / modv-modules.js View on Github external
presetData({ state }) {
    // @TODO: figure out a better clone than JSONparse(JSONstringify())
    const ajv = new Ajv({
      removeAdditional: 'all'
    })
    ajv.addMetaSchema(jsd4)

    const moduleNames = Object.keys(state.active).filter(
      key => key.substring(key.length - 8, key.length) !== '-gallery'
    )

    const moduleData = moduleNames.reduce((obj, moduleName) => {
      obj[moduleName] = {}
      obj[moduleName].values = Object.keys(
        state.active[moduleName].props || {}
      ).reduce((valuesObj, prop) => {
        valuesObj[prop] = state.active[moduleName][prop]
        return valuesObj
      }, {})
      return obj
    }, {})