Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'ajv' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
// @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.');
}
};
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;
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
}
'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;
}
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
}
}
_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;
}
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 }
}));
: 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
}
}
// 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.
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
}, {})