GREsau / okapi

OpenAPI (AKA Swagger) document generation for Rust projects
MIT License
631 stars 112 forks source link

Derive OpenApiResponderInner for #[derive(Responder)] enums #146

Open Keshi opened 8 months ago

Keshi commented 8 months ago

Using this feature https://github.com/rwf2/Rocket/issues/590 results in the trait bound '[...] rocket_okapi::response::OpenApiResponderInner' is not satisfied when the enum type is as a result type in a #[openapi] endpoint function.

It would be great if #[openapi] or similar could be used on an enum deriving Responder to also derive the appropriate forwarding OpenApiResponderInner implementation for the enum.

Example:

#[openapi] // inserting okapi openapi or derive macro here?
#[derive(Responder)]
enum MyResponse {
    Person(Json<Person>), // 200, json object
    Nothing(NoContent), // 204, no content
}

Should generate:

impl rocket_okapi::response::OpenApiResponderInner for MyResponse {
    fn responses(
        gen: &mut rocket_okapi::gen::OpenApiGenerator,
    ) -> rocket_okapi::Result<okapi::openapi3::Responses> {
        let mut responses = okapi::openapi3::Responses::default();
        responses
            .responses
            .extend(Json::<Person>::responses(gen)?.responses);
        responses
            .responses
            .extend(NoContent::responses(gen)?.responses);
        Ok(responses)
    }
}
ralpha commented 7 months ago

I would not use the #[openapi] syntax but instead use the #[derive(OpenApiResponderInner)].

This could then be done similar to https://github.com/GREsau/okapi/blob/1608ff7b92e3daca8cf05aa4594e1cf163e584a9/rocket-okapi-codegen/src/lib.rs#L119:L137

Some of the code could even be reused.

Feel free to create a MR to help with adding this.