poem-web / poem

A full-featured and easy-to-use web framework with the Rust programming language.
Apache License 2.0
3.62k stars 295 forks source link

OpenAPI: Trying to make a `time::OffsetDateTime` `#[oai(read_only)]` requires it to be Default-able, when it isn't #647

Open lyssieth opened 1 year ago

lyssieth commented 1 year ago

I'm trying to create a type that contains a time::OffsetDateTime, but trying to derive Object on it with the time field being #[oai(read_only)] (since it's determined by the server) fails to compile.

I'm unsure whether I'm doing everything as expected by the API, or in general correctly.

Expected Behavior

Compiling as expected, without any warnings

Actual Behavior

error[E0277]: the trait boundtime::OffsetDateTime: std::default::Defaultis not satisfied

Steps to Reproduce the Problem

# Cargo.toml (partial)
poem-openapi = { version = "3.0.4", features = ["time"] }
time = "0.3.28"
// src/lib.rs
use poem_openapi::Object;
use time::OffsetDateTime;

#[derive(Object)]
#[oai(read_only_all)]
struct Reproduction {
    time: OffsetDateTime,
}

And then trying to compile.

Specifications

sunli829 commented 1 year ago

It's not a bug, if you set this field to read-only, then this object will be given a default value (via Default::default) when used as a request, you may consider create a newtype MyOffsetDateTime, and implement Default::default for it.

lyssieth commented 1 year ago

Huh. That's definitely a bit strange, but I can understand it.

Is there a better way to handle a type that will only ever be returned from the server, and can't be sent to the server, then?

sunli829 commented 1 year ago

In v3.0.6 can use default to specify a function that creates a default value, which is more convenient than defining a newtype.

fn default_offset_datetime() -> OffsetDateTime {
    OffsetDateTime::now_utc()
}

#[derive(Debug, Object, PartialEq)]
struct Obj {
    #[oai(read_only, default = "default_offset_datetime")]
    time: OffsetDateTime,
}

I'll let you know when v3.0.5 is released. 🙂

lyssieth commented 1 year ago

Alright, thank you! I'll be keeping a keen eye out :>