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

Aliases for generic enum in body #817

Closed
javihc opened this issue Dec 4, 2023 · 3 comments · Fixed by #1034
Closed

Aliases for generic enum in body #817

javihc opened this issue Dec 4, 2023 · 3 comments · Fixed by #1034
Labels
Generics - Hard Stuff concerning generics implementation

Comments

@javihc
Copy link

javihc commented Dec 4, 2023

I am writting an API with Axum and I am using and enum to recevibe o single value or a list of values. For that I am using a Enum with a generic type T

pub enum OneOrMany<T> {
    /// A single value
    One(T),
    /// A list of values
    Many(Vec<T>),
}

To generate the OpenAPi I use aliases aliases(StringOneOrMany = OneOrMany<String>) and when I generate the openapi.json it serialize as

"StringOneOrMany": {
    "oneOf": [
        {
            "$ref": "#/components/schemas/T"
        },
        {
            "type": "array",
            "items": {
                "$ref": "#/components/schemas/T"
            },
            "description": "A list of values"
        }
    ]
},

How can I generate the schema correctly without using value_type=

pub enum OneOrMany<T> {
    #[schema(value_type = String)]
    /// A single value
    One(T),
    #[schema(value_type = Vec<String>)]
    /// A list of values
    Many(Vec<T>),
}

With schemars the is no problem.

@wuerges
Copy link

wuerges commented Jan 24, 2024

Hey. In my project, I've implemented the ToSchema trait manually. I added a constraint for T:

impl<'a, T: ToSchema<'a>> ToSchema<'a> for OneOrMany<T> {
    fn schema() -> (
        &'a str,
        utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
    ) {
        let (schema_name, schema) = T::schema();
        let object = /* your schema */;

        ("OneOrMany", RefOr::<Schema>::T(Schema::Object(object)))
    }
}

@juhaku juhaku added the Generics - Hard Stuff concerning generics implementation label Sep 9, 2024
@juhaku
Copy link
Owner

juhaku commented Sep 9, 2024

This will be fixed here with full generics support #1034

@wuerges
Copy link

wuerges commented Sep 27, 2024

Thank you very much!

@juhaku juhaku moved this from Done to Released in utoipa kanban Oct 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Generics - Hard Stuff concerning generics implementation
Projects
Status: Released
Development

Successfully merging a pull request may close this issue.

3 participants