Skip to content

Commit

Permalink
feat: #129 allow passing additional options to createAjvValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
josdejong committed Aug 22, 2022
1 parent 95960aa commit a66f230
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 15 deletions.
40 changes: 27 additions & 13 deletions src/lib/plugins/validator/createAjvValidator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,23 +67,23 @@ const schemaDefinitions = {
}
}

const invalidJson = {
firstName: 'John',
lastName: 'Doe',
gender: null,
age: '28',
availableToHire: true,
job: {
company: 'freelance',
role: 'developer',
salary: 100
}
}

describe('createAjvValidator', () => {
it('should create a validate function', () => {
const validate = createAjvValidator(schema, schemaDefinitions)

const invalidJson = {
firstName: 'John',
lastName: 'Doe',
gender: null,
age: '28',
availableToHire: true,
job: {
company: 'freelance',
role: 'developer',
salary: 100
}
}

assert.deepStrictEqual(validate(invalidJson), [
{
path: ['gender'],
Expand All @@ -96,5 +96,19 @@ describe('createAjvValidator', () => {
])
})

it('should pass additional Ajv options', () => {
const validate = createAjvValidator(schema, schemaDefinitions, {
allErrors: false
})

assert.deepStrictEqual(validate(invalidJson), [
{
path: ['gender'],
message: 'should be equal to one of: "male", "female"',
severity: 'warning'
}
])
})

// TODO: test support for draft04, draft-06, draft-07
})
8 changes: 6 additions & 2 deletions src/lib/plugins/validator/createAjvValidator.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Options as AjvOptions } from 'ajv'
import Ajv from 'ajv-dist'
import type { JSONData } from 'immutable-json-patch'
import { parsePath } from 'immutable-json-patch'
Expand All @@ -10,16 +11,19 @@ import { ValidationSeverity } from '../../types.js'
* @param [schemaDefinitions=undefined]
* An object containing JSON Schema definitions
* which can be referenced using $ref
* @param [ajvOptions] Optional extra options for Ajv
* @return Returns a validation function
*/
export function createAjvValidator(
schema: JSONData,
schemaDefinitions: JSONData = undefined
schemaDefinitions: JSONData = undefined,
ajvOptions: AjvOptions = undefined
): Validator {
const ajv = new Ajv({
allErrors: true,
verbose: true,
$data: true
$data: true,
...ajvOptions
})

if (schemaDefinitions) {
Expand Down

0 comments on commit a66f230

Please sign in to comment.