logo
pub enum MaybeUndefined<T> {
    Undefined,
    Null,
    Value(T),
}
Expand description

Similar to Option, but it has three states, undefined, null and x.

Example

use poem::{test::TestClient, IntoEndpoint};
use poem_openapi::{payload::Json, types::MaybeUndefined, Object, OpenApi, OpenApiService};
use tokio::sync::Mutex;
use serde_json::json;

#[derive(Object, Clone, Default)]
struct Resource {
    attr1: Option<i32>,
    attr2: Option<String>,
}

#[derive(Object)]
struct UpdateResourceRequest {
    attr1: MaybeUndefined<i32>,
    attr2: MaybeUndefined<String>,
}

struct Api {
    resource: Mutex<Resource>,
}

#[OpenApi]
impl Api {
    #[oai(path = "/get", method = "get")]
    async fn get_resource(&self) -> Json<Resource> {
        Json(self.resource.lock().await.clone())
    }

    #[oai(path = "/put", method = "put")]
    async fn update_resource(&self, req: Json<UpdateResourceRequest>) {
        let mut resource = self.resource.lock().await;

        match req.0.attr1 {
            MaybeUndefined::Null => resource.attr1 = None,
            MaybeUndefined::Value(value) => resource.attr1 = Some(value),
            MaybeUndefined::Undefined => {}
        }

        match req.0.attr2 {
            MaybeUndefined::Null => resource.attr2 = None,
            MaybeUndefined::Value(value) => resource.attr2 = Some(value),
            MaybeUndefined::Undefined => {}
        }
    }
}

let api_service = OpenApiService::new(
    Api {
        resource: Default::default(),
    },
    "Test",
    "1.0",
);

let cli = TestClient::new(api_service.into_endpoint());

cli.get("/get").send().await.assert_json(json!({"attr1": null, "attr2": null}));

cli.put("/put").body_json(&json!({"attr1": 100i32})).send().await.assert_status_is_ok();
cli.get("/get").send().await.assert_json(json!({"attr1": 100i32, "attr2": null}));

cli.put("/put").body_json(&json!({"attr1": null, "attr2": "abc"})).send().await.assert_status_is_ok();
cli.get("/get").send().await.assert_json(json!({"attr1": null, "attr2": "abc"}));

Variants

Undefined

Undefined

Null

Null

Value(T)

Value

Implementations

Create a MaybeUndefined<T> from Option<T>, returns MaybeUndefined::Undefined if this value is none.

Create a MaybeUndefined<T> from Option<T>, returns MaybeUndefined::Null if this value is none.

Returns true if the MaybeUndefined<T> is undefined.

Returns true if the MaybeUndefined<T> is null.

Returns true if the MaybeUndefined<T> contains value.

Returns None if the the MaybeUndefined<T> is undefined or null, otherwise returns Some(&T).

Returns None if the the MaybeUndefined<T> is undefined or null, otherwise returns Some(&mut T).

Converts the MaybeUndefined<T> to Option<T>.

Converts from &MaybeUndefined<T> to MaybeUndefined<&T>.

Converts the MaybeUndefined<T> to Option<Option<T>>.

Converts the MaybeUndefined<T> to Option<Option<&U>>.

Returns true if the MaybeUndefined<T> contains the given value.

Returns true if the MaybeUndefined<T> contains the given nullable value.

Maps a MaybeUndefined<T> to MaybeUndefined<U> by applying a function to the contained nullable value

Maps a MaybeUndefined<T> to MaybeUndefined<U> by applying a function to the contained value

Converts from MaybeUndefined<T> (or &MaybeUndefined<T>) to MaybeUndefined<&T::Target>.

Transposes a MaybeUndefined of a Result into a Result of a MaybeUndefined.

MaybeUndefined::Undefined will be mapped to Ok(MaybeUndefined::Undefined). MaybeUndefined::Null will be mapped to Ok(MaybeUndefined::Null). MaybeUndefined::Value(Ok(_)) and MaybeUndefined::Value(Err(_)) will be mapped to Ok(MaybeUndefined::Value(_)) and Err(_).

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Deserialize this value from the given Serde deserializer. Read more

Performs the conversion.

Performs the conversion.

Performs the conversion.

Feeds this value into the given Hasher. Read more

Feeds a slice of this type into the given Hasher. Read more

The type of the elements being iterated over.

Which kind of iterator are we turning this into?

Creates an iterator from a value. Read more

This method returns an Ordering between self and other. Read more

Compares and returns the maximum of two values. Read more

Compares and returns the minimum of two values. Read more

Restrict a value to a certain interval. Read more

Parse from serde_json::Value.

Parse from JSON string.

Parse from multipart field.

Parse from repeated multipart field.

Parse from parameter.

Parse from multiple parameters.

This method tests for self and other values to be equal, and is used by ==. Read more

This method tests for !=.

This method returns an ordering between self and other values if one exists. Read more

This method tests less than (for self and other) and is used by the < operator. Read more

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more

This method tests greater than (for self and other) and is used by the > operator. Read more

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Serialize this value into the given Serde serializer. Read more

Convert this value to HeaderValue.

Convert this value to Value.

Convert this value to JSON string.

If it is true, it means that this type is required.

The raw type used for validator. Read more

The raw element type used for validator.

Returns the name of this type

Get schema reference of this type.

Register this type to types registry.

Returns a reference to the raw value.

Returns an iterator for traversing the elements.

Returns true if this value is none. Read more

Returns true if this value is empty. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Compare self to key and return true if they are equal.

Performs the conversion.

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more