Skip to content

Commit

Permalink
Added derivations for Type, ParseFromJSON and ToJSON for sqlx::types:… (
Browse files Browse the repository at this point in the history
#833)

* Added derivations for Type, ParseFromJSON and ToJSON for sqlx::types::Json<T>

* cargo fmt

* Bugfixes

* Cargo fmt

* Formatting
  • Loading branch information
Nahuel-M authored Jul 27, 2024
1 parent b60d803 commit 1c46633
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions poem-openapi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ ipnet = { version = "2.7.1", optional = true }
prost-wkt-types = { version = "0.5.0", optional = true }
geo-types = { version = "0.7.12", optional = true }
geojson = { version = "0.24.1", features = ["geo-types"], optional = true }
sqlx = { version = "0.7.4", features = ["json", "postgres", "sqlite", "mysql"], optional = true }

[dev-dependencies]
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
Expand Down
2 changes: 2 additions & 0 deletions poem-openapi/src/types/external/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ mod optional;
mod prost_wkt_types;
mod regex;
mod slice;
#[cfg(feature = "sqlx")]
mod sqlx;
mod string;
#[cfg(feature = "time")]
mod time;
Expand Down
48 changes: 48 additions & 0 deletions poem-openapi/src/types/external/sqlx.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use std::borrow::Cow;

use serde_json::Value;

use crate::{
registry::MetaSchemaRef,
types::{ParseError, ParseFromJSON, ParseResult, ToJSON, Type},
};

impl<T: Type> Type for sqlx::types::Json<T> {
const IS_REQUIRED: bool = Self::RawValueType::IS_REQUIRED;

type RawValueType = T;

type RawElementValueType = T::RawElementValueType;

fn name() -> Cow<'static, str> {
Self::RawValueType::name()
}

fn schema_ref() -> MetaSchemaRef {
Self::RawValueType::schema_ref()
}

fn as_raw_value(&self) -> Option<&Self::RawValueType> {
Some(&self.0)
}

fn raw_element_iter<'a>(
&'a self,
) -> Box<dyn Iterator<Item = &'a Self::RawElementValueType> + 'a> {
self.0.raw_element_iter()
}
}

impl<T: ParseFromJSON> ParseFromJSON for sqlx::types::Json<T> {
fn parse_from_json(value: Option<Value>) -> ParseResult<Self> {
Self::RawValueType::parse_from_json(value)
.map(sqlx::types::Json)
.map_err(ParseError::propagate)
}
}

impl<T: ToJSON> ToJSON for sqlx::types::Json<T> {
fn to_json(&self) -> Option<Value> {
self.0.to_json()
}
}

0 comments on commit 1c46633

Please sign in to comment.