juhaku / utoipa

Simple, Fast, Code first and Compile time generated OpenAPI documentation for Rust
Apache License 2.0
2.46k stars 191 forks source link

Generating Schema for a new type string #1150

Open wyatt-herkamp opened 2 weeks ago

wyatt-herkamp commented 2 weeks ago

The ability to apply pattern to new types(Tuple structs with only one data type)

#[derive(ToSchema)]
#[schema(pattern = r#"^([a-zA-Z0-9_\-]{3,32}$)"#)]
struct Username(String);
impl utoipa::PartialSchema for Username {
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        utoipa::openapi::ObjectBuilder::new()
            .schema_type(utoipa::openapi::schema::SchemaType::new(
                utoipa::openapi::schema::Type::String,
            ))
            .pattern(Some(r#"^([a-zA-Z0-9_\-]{3,32}$)"#))
            .into()
    }
}
impl utoipa::ToSchema for Username {
    fn name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("Username")
    }
}

I am willing to add this feature. But I won't be able to look at it til next week.

juhaku commented 2 weeks ago

Okay, I am not quite sure what are you after with this? This seems to be quite special case and is not something that is generic for all users of utoipa?

wyatt-herkamp commented 2 weeks ago

Basically you should be able to set pattern or regex patterns on new types. Specifically a new type string

On Sun, Oct 20, 2024, 10:11 AM Juha Kukkonen @.***> wrote:

Okay, I am not quite sure what are you after with this? This seems to be quite special case and is not something that is generic for all users of utoipa?

— Reply to this email directly, view it on GitHub https://github.com/juhaku/utoipa/issues/1150#issuecomment-2424988829, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACZ5NZ2RUBB433GZE4IFQY3Z4O2YJAVCNFSM6AAAAABQFY3OXWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDIMRUHE4DQOBSHE . You are receiving this because you authored the thread.Message ID: @.***>

wyatt-herkamp commented 2 weeks ago

So for example

#[derive(ToSchema)]
#[schema(pattern = r#"^([a-zA-Z0-9_\-]{3,32}$)"#)]
struct Username(String);

It would generate the code like the above.

P.S I noticed that the way I worded my original issue was confusing.

juhaku commented 2 weeks ago

Right, now I get it. thanks :slightly_smiling_face: This seems duplicate for this https://github.com/juhaku/utoipa/issues/572.

If you find time please go ahead and submit a PR. This should be quite simple to do. It would need the unnamed struct features to parse some of those features currently parsed by named field features. It would be beneficial to add not just pattern, but other useful features as well.