Swagger Generation using OneOf for Inheritance

1.7k Views Asked by At

I am trying to use NSwag to generate a swagger document for my REST API. My response object contains a property that is an abstract class. I would like the schema to use oneOf for the child classes instead. For example my current output looks like this:

"Response": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
    "description": {
        "nullable": true,
        "status": {
            "nullable": true,
            "oneOf": [
            {
                "$ref": "#/components/schemas/Status"
            }
            ]
        }
    }
},
"Status": {
    "type": "object",
    "discriminator": {
        "propertyName": "descriminator",
        "mapping": {
            "TypeA": "#/components/schemas/TypeA",
            "TypeB": "#/components/schemas/TypeB"
        }
    },
    "x-abstract": true,
    "additionalProperties": false,
    "required": [
        "descriminator"
    ],
    "properties": {
        "id": {
            "type": "string",
            "nullable": true
        }
    }
},
"TypeA": {
    "allOf": [
    {
        "$ref": "#/components/schemas/Status"
    },
    {
        "type": "object",
        "additionalProperties": false,
        "properties": {
            "desc": {
                "type": "string",
                "nullable": true
            }
        }
    }
},
"TypeB": {
    "allOf": [
    {
        "$ref": "#/components/schemas/Status"
    },
    {
        "type": "object",
        "additionalProperties": false,
        "properties": {
            "name": {
                "type": "string",
                "nullable": true
            }
        }
    }
}

I would like instead for the Response object to look something like this:

"Response": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
    "description": {
        "nullable": true,
        "status": {
            "nullable": true,
            "oneOf": [
            {
                "$ref": "#/components/schemas/TypeA",
                "$ref": "#/components/schemas/TypeB"
            }
            ]
        }
    }
}

This document will not be used to generate any code and is instead more useful from a readability perspective. Any guidance on how I can get the output I am looking for? I have looked into custom JsonSchemaGenerators and custom JSchemaGenerationProviders but I'm afraid I have no idea how to start with those. I know schema generation does not have OneOf neatly built into it, so I have no idea how to add it modify the schema generation to use it.

0

There are 0 best solutions below