ajv-validator / ajv

The fastest JSON schema Validator. Supports JSON Schema draft-04/06/07/2019-09/2020-12 and JSON Type Definition (RFC8927)
https://ajv.js.org
MIT License
13.86k stars 877 forks source link

Picking or Omiting Certain Properties From a Schema Definition to make another definition #2484

Closed himittal09 closed 3 months ago

himittal09 commented 3 months ago

What version of Ajv you are you using? 8.17.1

What problem do you want to solve? Avoiding Repetition

What do you think is the correct solution to problem? Extending Existing Schemas

Will you be able to implement it? I Think not

Hello,

Is there any way to extend existing schemas in any way? Like consider the following schema:

const T1: JSONSchemaType<SomeType> = {
    type: 'object',
    required: ['p1', 'p2', 'p3'],
    properties: {
        p1: { type: 'string' },
        p2: { type: 'string' },
        p3: { type: 'string' }
    }
} as const;

Now, I want to make another schema to have all properties of schema T1, and some additional properties. (extending existing schema)

And yet another Schema, which should have all properties of T1, except some. ("Picking" or "Omitting" certain properties from existing schema.

Apologies if this feature already exists, I tried to read documentation at my best. Also, another similar library named Zod has this feature, if someone needs reference.

Thank you for help

jasoniangreen commented 3 months ago

Hi @himittal09 I have a few suggestions.

AJV has a lot of ways you can reuse schemas, plus there are a few javascript methods we can use too. Firstly you can checkout the features detailed in the combining schemas section of the docs. You can structure your validation logic across multiple schema files and have schemas reference each other using $ref keyword.

You can also, however, just treat your schema the way you would any javascript object and use standard code reuse patterns:

const T1: JSONSchemaType<SomeType> = {
    type: 'object',
    required: ['p1', 'p2', 'p3'],
    properties: {
        p1: { type: 'string' },
        p2: { type: 'string' },
        p3: { type: 'string' }
    }
} as const;

const T2: JSONSchemaType<SomeType> = {
    ...T1,
    required: ['p1'],
    additionalProperties: false
} as const;

And of course there are many libraries that can help with methods like _.pick and _.omit from underscore.