How to use the ajv function in ajv

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 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 airtasker / spot / lib / src / testing / test-runner.ts View on Github external
private verifyBody(
    expectedResponse: DefaultResponseDefinition,
    response: AxiosResponse,
    typeStore: TypeNode[]
  ): boolean {
    if (!expectedResponse.body) {
      return true;
    }

    const jsv = new JsonSchemaValidator();
    const schema = {
      ...jsonTypeSchema(expectedResponse.body.type),
      definitions: typeStore.reduce<{ [key: string]: JsonSchemaType }>(
        (defAcc, typeNode) => {
          return { [typeNode.name]: jsonTypeSchema(typeNode.type), ...defAcc };
        },
        {}
      )
    };
    const validateFn = jsv.compile(schema);
    const valid = validateFn(response.data);
    if (valid) {
      this.logger.success("Body compliant", { indent: 2 });
      return true;
    }
    this.logger.error(
github SCADA-LTS / Scada-LTS / ScadaLTS-UI-1 / src / components / ExportImportPointHierarchy.vue View on Github external
parse() {
        this.showStatus(
          this.constants.STATUS,
          this.constants.STATUS_INFO.RUN,
          "Start");
        this.showStatus(
          this.constants.STATUS_GROUP,
          this.constants.STATUS_GROUP_INFO.PARSE,
          "Validate");


        let ajv = new Ajv();
        let validate = ajv.compile(this.constants.SCHEMA);
        let valid = validate(this.json);
        if (!valid) {
          console.log(validate.errors);
          this.showStatus(
            this.constants.STATUS,
            this.constants.STATUS_INFO.ERROR,
            validate.errors);
        } else {
          try {
            let folders = this.json.folders;
            this.base.xidFolderAfter = folders.slice();
            this.base.counterToParse = this.base.xidFolderAfter.length;
            if (folders == undefined) {
              this.showStatus(
                this.constants.STATUS,
github xogeny / denada-js / src / denada.ts View on Github external
export function matchValue(val: any, schema: object) {
    if (schema === null) return val === schema;
    if (typeof schema !== "object") {
        console.warn(`Expected schema to be an object, but got ${typeof schema} instead`);
        return false;
    }

    const validator = new Ajv();
    validator.validateSchema(schema);
    const result = validator.validate(schema, val);
    if (result === true) {
        return true;
    } else if (result === false) {
        return false;
    } else {
        throw new Error("Validation required a schema with $ref...only synchronous validation is supported");
    }
}
github vazco / uniforms / docs / examples / Tutorial / GuestSchema4.js View on Github external
import Ajv from 'ajv';
import ImageField from './ImageField.js';
import LongTextField from 'uniforms-unstyled/LongTextField';
import { JSONSchemaBridge } from 'uniforms-bridge-json-schema';

const ajv = new Ajv({ allErrors: true, useDefaults: true });

const schema = {
  title: 'Guest',
  type: 'object',
  properties: {
    firstName: { type: 'string' },
    lastName: { type: 'string' },
    workExperience: {
      description: 'Work experience in years',
      type: 'integer',
      minimum: 0,
      maximum: 100
    },
    profession: {
      type: 'string',
      options: [
github iodide-project / iodide / src / editor / reducers / create-validated-reducer.js View on Github external
const createValidatedReducer = (reducer, schema, options) => {
  const ajv = new Ajv(options);
  const validate = ajv.compile(schema);

  const validatedReducer = (state, action) => {
    const futureState = reducer(state, action);

    if (!validate(futureState)) {
      const badValues = {};
      validate.errors.forEach(error => {
        if (error.dataPath !== undefined) {
          const dataPath =
            error.dataPath[0] === "."
              ? error.dataPath.slice(1)
              : error.dataPath;
          badValues[dataPath] = _.get(futureState, dataPath);
        }
      });
github josdejong / jsoneditor / src / jsoneditor / components / TextMode.js View on Github external
setSchema (schema) {
    if (schema) {
      const ajv = this.props.ajv || (Ajv && Ajv(AJV_OPTIONS))

      if (!ajv) {
        throw new Error('Cannot validate JSON: ajv not available. ' +
            'Provide ajv via options or use a JSONEditor bundle including ajv.')
      }

      this.setState({
        compiledSchema: ajv.compile(schema)
      })
    }
    else {
      this.setState({
        compiledSchema: null
      })
    }
  }
github reimagined / resolve / packages / core / resolve-scripts / src / validate_config.js View on Github external
import Ajv from 'ajv'
import Trie from 'route-trie'

import { schemaResolveConfig, message } from './constants'
import { checkRuntimeEnv } from './declare_runtime_env'

const ajv = new Ajv()

const allowedMethods = [
  'HEAD',
  'GET',
  'POST',
  'PUT',
  'DELETE',
  'PATCH',
  'OPTIONS',
  'ALL'
]

export const validateReadModelConnectors = resolveConfig => {
  for (const { connectorName } of [
    ...resolveConfig.readModels,
    ...resolveConfig.sagas