juhaku / utoipa

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

`std::time::SystemTime` support #1222

Open SamuelMarks opened 1 day ago

SamuelMarks commented 1 day ago

the trait bound SystemTime: ToSchema is not satisfied

error[E0277]: the trait bound SystemTime: PartialSchema is not satisfied

I've tried enabling crate features of chrono or time; to no avail.

#[derive(
    Debug,
    Clone,
    serde::Serialize,
    serde::Deserialize,
    diesel::AsChangeset,
    utoipa::ToSchema,
    PartialEq,
    Default,
)]
pub struct S {
    pub t: Option<std::time::SystemTime>,
}

How do I get this to work?

juhaku commented 1 day ago

This is actually same issue as with any other type that does not implement ToSchema by default. See more details here: https://github.com/juhaku/utoipa/issues/1205#issuecomment-2478694544

There would be a need to add support for the SystemTime to utoipa-gen the way the support has been added to chono and other similar types.

SamuelMarks commented 23 hours ago

@juhaku Hmm, so something like:

#[derive(ToSchema)]
#[schema(as = SystemTime, value_type = SystemTime)]
struct MySystemTime(SystemTime);

Or more something like:

impl PrimitiveType {
    pub fn new(path: &Path) -> Option<PrimitiveType> {
        let last_segment = path.segments.last().unwrap_or_else(|| {
            panic!(
                "Path for DefaultType must have at least one segment: `{path}`",
                path = path.to_token_stream()
            )
        });

        let name = &*last_segment.ident.to_string();

        let ty: syn::Type = match name {
            "String" | "str" | "char" => syn::parse_quote!(#path),

            "bool" => syn::parse_quote!(#path),

            "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64"
            | "u128" | "usize" => syn::parse_quote!(#path),
            "f32" | "f64" => syn::parse_quote!(#path),

            "SystemTime" => syn::parse_quote!(#SystemTime),

Or even combine the two:

"SystemTime" => syn::parse_quote!(#MySystemTime),
SamuelMarks commented 22 hours ago

FWIW: In the interim; for this project; I've switched to chrono from diesel up to utoipa.

juhaku commented 22 hours ago

How the SytemTime renders when it is serialized to JSON? Is it a number in seconds or is it a string? Depending on the type you can locally alias it with value_type.

[derive(ToSchema)]
#[schema(as = SystemTime, value_type = String)] // This will treat it as a String, 
struct MySystemTime(SystemTime);
juhaku commented 22 hours ago

But in order to make utoipa support the SystemTime internally, the schema type conversion should be implemented here: https://github.com/juhaku/utoipa/blob/a0c3415cde5f932943bbebe4a3cafc03e1519fe3/utoipa-gen/src/schema_type.rs#L253