Skip to content

Commit

Permalink
Merge pull request #1284 from ajv-validator/v7-alpha-error-params
Browse files Browse the repository at this point in the history
V7 alpha error params
  • Loading branch information
epoberezkin committed Sep 17, 2020
2 parents c5c1b84 + bb342fd commit 04775b1
Show file tree
Hide file tree
Showing 51 changed files with 424 additions and 262 deletions.
4 changes: 2 additions & 2 deletions .github/ISSUE_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ This template is for bug or error reports. For other issues please use:
<!-- See https://github.com/ajv-validator/ajv#options -->

```javascript

```

**JSON Schema**
Expand All @@ -25,7 +26,6 @@ This template is for bug or error reports. For other issues please use:

```json


```

**Sample data**
Expand All @@ -34,7 +34,6 @@ This template is for bug or error reports. For other issues please use:

```json


```

**Your code**
Expand All @@ -51,6 +50,7 @@ Thank you!
-->

```javascript

```

**Validation result, data AFTER validation, error messages**
Expand Down
5 changes: 2 additions & 3 deletions .github/ISSUE_TEMPLATE/bug-or-error-report.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ For other issues please see https://github.com/ajv-validator/ajv/blob/master/CON
<!-- See https://github.com/ajv-validator/ajv#options -->

```javascript

```

**JSON Schema**
Expand All @@ -29,7 +30,6 @@ For other issues please see https://github.com/ajv-validator/ajv/blob/master/CON

```json


```

**Sample data**
Expand All @@ -38,7 +38,6 @@ For other issues please see https://github.com/ajv-validator/ajv/blob/master/CON

```json


```

**Your code**
Expand All @@ -55,13 +54,13 @@ Thank you!
-->

```javascript

```

**Validation result, data AFTER validation, error messages**

```
```

**What results did you expect?**
Expand Down
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ Please make it as small as posssible to reproduce the issue
-->

```typescript

```

**Typescript compiler error messages**

```
```

**Describe the change that should be made to address the issue?**
Expand Down
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@ spec/JSON-Schema-Test-Suite
.browser
coverage
dist
bundle
.nyc_output
spec/_json
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,13 +343,16 @@ JSON Schema specification defines several annotation keywords that describe sche

## Formats

From version 7 Ajv does not include formats defined by JSON Schema specification - these and several others formats are provided by [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin.
From version 7 Ajv does not include formats defined by JSON Schema specification - these and several other formats are provided by [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin.

To add all formats from this plugin:

```javascript
import Ajv from "ajv"
import addFormats from "ajv-formats"

const ajv = new Ajv()
require("ajv-formats")(ajv)
addFormats(ajv)
```

See ajv-formats documentation for further details.
Expand All @@ -362,7 +365,7 @@ The following formats are defined in [ajv-formats](https://github.com/ajv-valida

- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).
- _time_: time with optional time-zone.
- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)).
- _date-time_: date-time from the same source (time-zone is mandatory).
- _uri_: full URI.
- _uri-reference_: URI reference, including full and relative URIs.
- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570)
Expand All @@ -378,12 +381,10 @@ The following formats are defined in [ajv-formats](https://github.com/ajv-valida

**Please note**: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. These formats are available in [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) plugin.

You can add (and replace) any formats using [addFormat](#api-addformat) method.
You can add and replace any formats using [addFormat](#api-addformat) method.

The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details.

You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js).

## <a name="ref"></a>Combining schemas with \$ref

You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword.
Expand Down
3 changes: 3 additions & 0 deletions lib/ajv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export {
FormatDefinition,
AsyncFormatDefinition,
KeywordDefinition,
KeywordErrorDefinition,
CodeKeywordDefinition,
MacroKeywordDefinition,
FuncKeywordDefinition,
Expand All @@ -12,6 +13,7 @@ export {
Options,
ValidateFunction,
AsyncValidateFunction,
ErrorObject,
CacheInterface,
Logger,
} from "./types"
Expand All @@ -22,6 +24,7 @@ export interface Plugin<Opts> {

import KeywordCxt from "./compile/context"
export {KeywordCxt}
export {DefinedError} from "./vocabularies/errors"

import type {
Schema,
Expand Down
3 changes: 3 additions & 0 deletions lib/compile/validate/dataType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {
SchemaObjCxt,
KeywordErrorDefinition,
KeywordErrorCxt,
ErrorObject,
AnySchemaObject,
} from "../../types"
import type {ValidationRules} from "../rules"
Expand Down Expand Up @@ -134,6 +135,8 @@ function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, e
)
}

export type TypeError = ErrorObject<"type", {type: string}>

const typeError: KeywordErrorDefinition = {
message: ({schema}) => str`should be ${schema}`,
params: ({schema, schemaValue}) =>
Expand Down
10 changes: 1 addition & 9 deletions lib/refs/json-schema-draft-06.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,7 @@
"allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
},
"simpleTypes": {
"enum": [
"array",
"boolean",
"integer",
"null",
"number",
"object",
"string"
]
"enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
},
"stringArray": {
"type": "array",
Expand Down
10 changes: 1 addition & 9 deletions lib/refs/json-schema-draft-07.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,7 @@
"allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
},
"simpleTypes": {
"enum": [
"array",
"boolean",
"integer",
"null",
"number",
"object",
"string"
]
"enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
},
"stringArray": {
"type": "array",
Expand Down
10 changes: 5 additions & 5 deletions lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,14 @@ export interface AsyncValidateFunction<T = any> extends ValidateFunction<T> {

export type AnyValidateFunction<T = any> = ValidateFunction<T> | AsyncValidateFunction<T>

export interface ErrorObject {
keyword: string
export interface ErrorObject<K = string, P = Record<string, any>> {
keyword: K
dataPath: string
schemaPath: string
params: Record<string, unknown> // TODO add interface
// Added to validation errors of propertyNames keyword schema
params: P
// Added to validation errors of "propertyNames" keyword schema
propertyName?: string
// Excluded if messages set to false.
// Excluded if option `messages` set to false.
message?: string
// These are added with the `verbose` option.
schema?: unknown
Expand Down
18 changes: 11 additions & 7 deletions lib/vocabularies/applicator/additionalItems.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import type {CodeKeywordDefinition} from "../../types"
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import type KeywordCxt from "../../compile/context"
import {alwaysValidSchema, checkStrictMode} from "../util"
import {applySubschema, Type} from "../../compile/subschema"
import {_, Name, str} from "../../compile/codegen"

export type AdditionalItemsError = ErrorObject<"additionalItems", {limit: number}>

const error: KeywordErrorDefinition = {
message: ({params: {len}}) => str`should NOT have more than ${len} items`,
params: ({params: {len}}) => _`{limit: ${len}}`,
}

const def: CodeKeywordDefinition = {
keyword: "additionalItems",
keyword: "additionalItems" as const,
type: "array",
schemaType: ["boolean", "object"],
before: "uniqueItems",
error,
code(cxt: KeywordCxt) {
const {gen, schema, parentSchema, data, it} = cxt
const len = gen.const("len", _`${data}.length`)
Expand All @@ -33,10 +41,6 @@ const def: CodeKeywordDefinition = {
})
}
},
error: {
message: ({params: {len}}) => str`should NOT have more than ${len} items`,
params: ({params: {len}}) => _`{limit: ${len}}`,
},
}

module.exports = def
export default def
20 changes: 12 additions & 8 deletions lib/vocabularies/applicator/additionalProperties.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import type {CodeKeywordDefinition, KeywordErrorCxt} from "../../types"
import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
import {allSchemaProperties, schemaRefOrVal, alwaysValidSchema, usePattern} from "../util"
import {applySubschema, SubschemaApplication, Type} from "../../compile/subschema"
import {_, nil, or, Code, Name} from "../../compile/codegen"
import N from "../../compile/names"

export type AdditionalPropertiesError = ErrorObject<
"additionalProperties",
{additionalProperty: string}
>

const error: KeywordErrorDefinition = {
message: "should NOT have additional properties",
params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
}

const def: CodeKeywordDefinition = {
keyword: "additionalProperties",
type: "object",
schemaType: ["boolean", "object", "undefined"], // "undefined" is needed to support option removeAdditional: "all"
trackErrors: true,
error,
code(cxt) {
const {gen, schema, parentSchema, data, errsCount, it} = cxt
if (!errsCount) throw new Error("ajv implementation error")
Expand Down Expand Up @@ -91,13 +102,6 @@ const def: CodeKeywordDefinition = {
applySubschema(it, subschema, valid)
}
},
error: {
message: "should NOT have additional properties",
params: ({params}: KeywordErrorCxt): Code =>
_`{additionalProperty: ${params.additionalProperty}}`,
},
}

module.exports = def

export default def
2 changes: 1 addition & 1 deletion lib/vocabularies/applicator/allOf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ const def: CodeKeywordDefinition = {
},
}

module.exports = def
export default def
2 changes: 1 addition & 1 deletion lib/vocabularies/applicator/anyOf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,4 @@ const def: CodeKeywordDefinition = {
},
}

module.exports = def
export default def
2 changes: 1 addition & 1 deletion lib/vocabularies/applicator/contains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,4 @@ const def: CodeKeywordDefinition = {
},
}

module.exports = def
export default def
44 changes: 31 additions & 13 deletions lib/vocabularies/applicator/dependencies.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import type {CodeKeywordDefinition, SchemaMap, AnySchema} from "../../types"
import type {
CodeKeywordDefinition,
ErrorObject,
KeywordErrorDefinition,
SchemaMap,
AnySchema,
} from "../../types"
import type KeywordCxt from "../../compile/context"
import {alwaysValidSchema, propertyInData} from "../util"
import {applySubschema} from "../../compile/subschema"
Expand All @@ -11,10 +17,33 @@ interface PropertyDependencies {

type SchemaDependencies = SchemaMap

export type DependenciesError = ErrorObject<
"dependencies",
{
property: string
missingProperty: string
depsCount: number
deps: string // TODO change to string[]
}
>

const error: KeywordErrorDefinition = {
message: ({params: {property, depsCount, deps}}) => {
const property_ies = depsCount === 1 ? "property" : "properties"
return str`should have ${property_ies} ${deps} when property ${property} is present`
},
params: ({params: {property, depsCount, deps, missingProperty}}) =>
_`{property: ${property},
missingProperty: ${missingProperty},
depsCount: ${depsCount},
deps: ${deps}}`, // TODO change to reference
}

const def: CodeKeywordDefinition = {
keyword: "dependencies",
type: "object",
schemaType: "object",
error,
code(cxt: KeywordCxt) {
const {gen, schema, data, it} = cxt
const [propDeps, schDeps] = splitDependencies()
Expand Down Expand Up @@ -71,17 +100,6 @@ const def: CodeKeywordDefinition = {
}
}
},
error: {
message: ({params: {property, depsCount, deps}}) => {
const property_ies = depsCount === 1 ? "property" : "properties"
return str`should have ${property_ies} ${deps} when property ${property} is present`
},
params: ({params: {property, depsCount, deps, missingProperty}}) =>
_`{property: ${property},
missingProperty: ${missingProperty},
depsCount: ${depsCount},
deps: ${deps}}`, // TODO change to reference?
},
}

module.exports = def
export default def

0 comments on commit 04775b1

Please sign in to comment.