openapi-contrib / openapi-schema-to-json-schema

Due to the OpenAPI v3.0 and JSON Schema discrepancy, you can use this JS library to convert OpenAPI Schema objects to proper JSON Schema.
https://www.npmjs.com/package/@openapi-contrib/openapi-schema-to-json-schema
MIT License
242 stars 20 forks source link

Combiners (anyOf, allOf, oneOf) + nullable #76

Open toomuchdesign opened 3 weeks ago

toomuchdesign commented 3 weeks ago

Good afternoon! I'm writing to ask feedback about a possible conversion case that could be not handled by this library: combiners + nullable.

const schema = {
  nullable: true,
  allOf: [
    {
      type: "object",
      required: ["foo"],
      properties: {
        foo: {
          type: "integer",
        },
      },
    },
  ],
};

Currently the output strips nullable: true out, but it doesn't seem right. The most plausible solution I can think of is the following, but I'd like to hear your thoughts about it.

const schema = {
  oneOf: [
    {
      type: "null",
    },
    {
      allOf: [
        {
          type: "object",
          required: ["foo"],
          properties: {
            foo: {
              type: "integer",
            },
          },
        },
      ],
    },
  ],
};

The approach above, beside being a valid OAS definition, seems to be a legit OAS 3.0.0 workaround to define nullable $ref properties.

// This is OAS invalid since you can't extend `$ref` definitions
const schema = {
  type: "object"
  properties: {
    foo: {
      $ref: '#/components/schemas/MyReferencedComponent'
      nullable: true
    }
  }
}

// This seems to be a valid workaround
const schema = {
  type: "object",
  properties: {
    foo: {
      allOf: [{ $ref: "#/components/schemas/MyReferencedComponent" }],
      nullable: true,
    },
  },
};

Happy to open a PR if the described use case seems legit. Cheers!