Skip to content

Conversation

@kapouer
Copy link
Contributor

@kapouer kapouer commented Apr 13, 2022

JSON Schema's OpenAPI specification allows some sort of schema inheritance:
https://ajv.js.org/json-schema.html#discriminator

To support this, objection's ajv "patch" validator should keep required field when it sits next a discriminator keyword.

To keep the change minimal, ajvNoDefaults.opts.discriminator is not checked to know if there is actual support for that keyword.

@kapouer
Copy link
Contributor Author

kapouer commented Apr 13, 2022

NB this might help for issues like #1130.

@kapouer
Copy link
Contributor Author

kapouer commented Apr 13, 2022

But this PR does not work with that case:

const Ajv = require("ajv")
const ajv = new Ajv({allErrors: true, strictSchema: true, discriminator: true, validateSchema: true})

const schema = {
  type: "object",
  properties: {
    foo: {type: "string"},
    bar: {type: "number", maximum: 3},
  },
  discriminator: { propertyName: 'test' },
  required: ["foo", "bar", "test"],
  oneOf: [{
    properties: {
        test: { const: 'one' },
        testa: { type: 'string' },
    },        
  }, {
    properties: {
        test: { const: 'two' },
        testb: { type: 'string' },
    },        
  },]
}

const validate = ajv.compile(schema)

test({foo: "abc", bar: 2, test: 'one', testa: 'toto'})
test({foo: 2, bar: 4, test: 'two', testb: 'tata'})

function test(data) {
  const valid = validate(data)
  if (valid) console.log("Valid!")
  else console.log("Invalid: " + ajv.errorsText(validate.errors))
}

It's actually possible to have shared properties + a discriminator.

@kapouer
Copy link
Contributor Author

kapouer commented Apr 13, 2022

Force-pushed to fix it.

@lehni
Copy link
Collaborator

lehni commented Jun 30, 2023

LGTM, thanks!

@kapouer
Copy link
Contributor Author

kapouer commented Jun 30, 2023

Much appreciated

@lehni lehni merged commit dc966e5 into Vincit:master Jun 30, 2023
@lehni
Copy link
Collaborator

lehni commented Jul 20, 2023

Released in v3.0.5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants