Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to require one or another object property with fluent-json-schema ? #949

Open
DamienGarrido opened this issue Oct 12, 2023 · 1 comment
Labels
help wanted Extra attention is needed

Comments

@DamienGarrido
Copy link

How to require one or another object property with fluent-json-schema?

I'm trying to generate the following JSON schema using fluent-json-schema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "anyOf": [{ "required": ["id"] }, { "required": ["account"] }],
  "properties": {
    "name": { "type": "string" },
    "id": { "type": "integer" },
    "account": { "type": "string" }
  },
  "required": ["name"]
}

I need the name property to be mandatory, and either the id or the account property to be present.

I've been able to generate the schema only by using the raw() method (see below).

const { S } = require('fluent-json-schema');

const jsonSchema = S.object()
  .raw({ anyOf: [{ required: ['id'] }, { required: ['account'] }] })
  .prop('name', S.string().required())
  .prop('id', S.integer())
  .prop('account', S.string());

See test code on fluent-json-schema-validate-one-of-two-properties Replit.

How can I generate this JSON schema without using the raw() method?

Your Environment

  • node version: 18
  • fluent-json-schema version: 4.2.0-beta.0
  • os: Linux
@DamienGarrido DamienGarrido added the help wanted Extra attention is needed label Oct 12, 2023
@bortolottidev
Copy link

Hey! I achieved a possible solution with this schema:

const jsonSchema = S.object()
  .prop('name', S.string().required())
  .ifThenElse(
    S.object().prop('id', S.not(S.integer())),
    S.object().prop('account', S.string().required()),
    S.object().ifThen(
      S.object().prop('account', S.not(S.string())),
      S.object().prop('id', S.integer().required())
    )
  )

It handles one or both account & id with a valid value without using raw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants