Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add axum support #30

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,20 @@ edition = "2021"

[dependencies]
serde_json = { version = "1.0", optional = true }
serde = { version = "1.0", optional = true }
serde-cs = { version = "0.2.4", optional = true }
actix-web = { version = "4.3.0", optional = true }
axum = { version = "0.6.4", features = ["json"], optional = true }
http = { version = "0.2.8" , optional = true}
futures = { version = "0.3.25", optional = true }
deserr-internal = { version = "=0.3.0", path = "derive" }

[features]
default = ["serde-json", "serde-cs", "actix-web"]
default = ["serde-json", "serde-cs", "actix-web", "axum"]
serde-json = ["serde_json"]
serde-cs = ["dep:serde-cs"]
actix-web = ["dep:actix-web", "futures"]
axum = ["dep:axum", "http", "serde"]

[dev-dependencies]
automod = "1.0"
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# Deserr
![Crates.io](https://img.shields.io/crates/v/deserr)
![docs.rs](https://img.shields.io/docsrs/deserr)

## Introduction

Expand Down
3 changes: 1 addition & 2 deletions examples/actix_web_server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
name = "actix_web_server"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
publish = false
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice


[dependencies]
actix-http = { version = "3.2.2", default-features = false, features = ["compress-brotli", "compress-gzip", "rustls"] }
Expand Down
13 changes: 13 additions & 0 deletions examples/axum/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "example_axum"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
deserr = { path = "../../" }
axum = { version = "0.6.4", features = ["json"]}
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0.152", features = ["derive"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
125 changes: 125 additions & 0 deletions examples/axum/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::post;
use axum::Json;
use axum::Router;
use deserr::axum::AxumJson;
use deserr::take_cf_content;
use deserr::DeserializeError;
use deserr::Deserr;
use deserr::ErrorKind;
use deserr::JsonError;
use deserr::ValuePointerRef;
use serde::Deserialize;
use serde::Serialize;
use std::convert::Infallible;
use std::net::SocketAddr;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

#[derive(Debug, Serialize, Deserialize, Deserr)]
#[serde(deny_unknown_fields)]
#[deserr(deny_unknown_fields)]
struct Query {
name: String,

// deserr don't do anything strange with `Option`, if you don't
// want to make the `Option` mandatory specify it.
#[deserr(default)]
number: Option<i32>,

// you can put expression in the default values
#[serde(default = "default_range")]
#[deserr(default = Range { min: 2, max: 4 })]
range: Range,

// serde support a wide variety of enums, but deserr only support
// tagged enums, or unit enum as value.
#[serde(rename = "return")]
#[deserr(rename = "return")]
returns: Return,
}

fn default_range() -> Range {
Range { min: 2, max: 4 }
}

#[derive(Debug, Serialize, Deserialize, Deserr)]
#[serde(deny_unknown_fields)]
#[deserr(deny_unknown_fields, validate = validate_range -> __Deserr_E)]
struct Range {
min: u8,
max: u8,
}

// Here we could specify the error type we're going to return or stay entirely generic so the
// final caller can decide which implementation of error handler will generate the error message.
fn validate_range<E: DeserializeError>(
range: Range,
location: ValuePointerRef,
) -> Result<Range, E> {
if range.min > range.max {
Err(take_cf_content(E::error::<Infallible>(
None,
ErrorKind::Unexpected {
msg: format!(
"`max` (`{}`) should be greater than `min` (`{}`)",
range.max, range.min
),
},
location,
)))
} else {
Ok(range)
}
}

#[derive(Debug, Serialize, Deserialize, Deserr)]
#[serde(rename_all = "camelCase")]
#[deserr(rename_all = camelCase)]
enum Return {
Name,
Number,
}

/// This handler uses the official `axum::Json` extractor
async fn serde(Json(item): Json<Query>) -> Result<Json<Query>, impl IntoResponse> {
if item.range.min > item.range.max {
Err((
StatusCode::BAD_REQUEST,
format!(
"`max` (`{}`) should be greater than `min` (`{}`)",
item.range.max, item.range.min
),
)
.into_response())
} else {
Ok(Json(item))
}
}

/// This handler uses the official `AxumJson` deserr
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// This handler uses the official `AxumJson` deserr
/// This handler uses the official `AxumJson` deserr extractor

async fn deserr(item: AxumJson<Query, JsonError>) -> AxumJson<Query, JsonError> {
item
}

#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_axum=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();

let app = Router::new()
.route("/serde", post(serde))
.route("/deserr", post(deserr));

let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
5 changes: 5 additions & 0 deletions src/axum/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#[cfg(feature = "serde-json")]
mod serde_json;

#[cfg(feature = "serde-json")]
pub use self::serde_json::AxumJson;
85 changes: 85 additions & 0 deletions src/axum/serde_json.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use crate::{DeserializeError, Deserr, JsonError};
use axum::async_trait;
use axum::body::HttpBody;
use axum::extract::rejection::JsonRejection;
use axum::extract::FromRequest;
use axum::response::IntoResponse;
use axum::{BoxError, Json};
use http::{Request, StatusCode};
use std::marker::PhantomData;

/// Extractor for typed data from Json request payloads
/// deserialised by deserr.
///
/// ## Extractor
/// To extract typed data from a request body, the inner type `T` must implement the
/// [`deserr::Deserr<E>`] trait. The inner type `E` must implement the
/// [`DeserializeError`] trait.
///
/// ## Response
/// [`axum::IntoResponse`] is implemented for any `AxumJson<T, E>`
/// where `T` implement [`serde::Serialize`].
#[derive(Debug)]
pub struct AxumJson<T, E>(pub T, PhantomData<E>);

#[derive(Debug)]
pub enum AxumJsonRejection {
DeserrError(JsonError),
JsonRejection(JsonRejection),
}
Comment on lines +25 to +29
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should let the end user decide which kind of error they want to return.

Suggested change
#[derive(Debug)]
pub enum AxumJsonRejection {
DeserrError(JsonError),
JsonRejection(JsonRejection),
}
#[derive(Debug)]
pub enum AxumJsonRejection<E: DeserializeError> {
DeserrError(E),
JsonRejection(JsonRejection),
}


impl<T, E> IntoResponse for AxumJson<T, E>
where
T: serde::Serialize,
{
fn into_response(self) -> axum::response::Response {
Json(self.0).into_response()
}
}

#[async_trait]
impl<T, S, B, E: DeserializeError> FromRequest<S, B> for AxumJson<T, E>
where
T: Deserr<E>,
E: DeserializeError + 'static,
B: HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<BoxError>,
S: Send + Sync,
AxumJsonRejection: std::convert::From<E>,
{
type Rejection = AxumJsonRejection;

async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
let Json(value): Json<serde_json::Value> = Json::from_request(req, state).await?;
let data = deserr::deserialize::<_, _, _>(value)?;
Ok(AxumJson(data, PhantomData))
}
}
Comment on lines +40 to +58
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#[async_trait]
impl<T, S, B, E: DeserializeError> FromRequest<S, B> for AxumJson<T, E>
where
T: Deserr<E>,
E: DeserializeError + 'static,
B: HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<BoxError>,
S: Send + Sync,
AxumJsonRejection: std::convert::From<E>,
{
type Rejection = AxumJsonRejection;
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
let Json(value): Json<serde_json::Value> = Json::from_request(req, state).await?;
let data = deserr::deserialize::<_, _, _>(value)?;
Ok(AxumJson(data, PhantomData))
}
}
#[async_trait]
impl<T, S, B, E: DeserializeError> FromRequest<S, B> for AxumJson<T, E>
where
T: Deserr<E>,
E: DeserializeError + 'static,
B: HttpBody + Send + 'static,
B::Data: Send,
B::Error: Into<BoxError>,
S: Send + Sync,
{
type Rejection = AxumJsonRejection<E>;
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
let Json(value): Json<serde_json::Value> = Json::from_request(req, state).await?;
let data = deserr::deserialize::<_, _, _>(value)?;
Ok(AxumJson(data, PhantomData))
}
}


impl From<JsonError> for AxumJsonRejection {
fn from(value: JsonError) -> Self {
AxumJsonRejection::DeserrError(value)
}
}
Comment on lines +60 to +64
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
impl From<JsonError> for AxumJsonRejection {
fn from(value: JsonError) -> Self {
AxumJsonRejection::DeserrError(value)
}
}

I don't think we can keep this while being fully generic over the error type.


impl From<JsonRejection> for AxumJsonRejection {
fn from(value: JsonRejection) -> Self {
AxumJsonRejection::JsonRejection(value)
}
}

impl IntoResponse for AxumJsonRejection {
fn into_response(self) -> axum::response::Response {
match self {
AxumJsonRejection::DeserrError(e) => e.into_response(),
AxumJsonRejection::JsonRejection(e) => e.into_response(),
}
}
}
Comment on lines +72 to +79
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe in the previous comments, we were supposed to also constraint E to implement IntoResponse?


impl IntoResponse for JsonError {
fn into_response(self) -> axum::response::Response {
(StatusCode::BAD_REQUEST, self.to_string()).into_response()
}
}
Comment on lines +81 to +85
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is nice though, it will help someone who don't want to use his own error type 👍

4 changes: 2 additions & 2 deletions src/impls.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
take_cf_content, DeserializeError, Deserr, ErrorKind, IntoValue, Map, Sequence,
Value, ValueKind, ValuePointerRef,
take_cf_content, DeserializeError, Deserr, ErrorKind, IntoValue, Map, Sequence, Value,
ValueKind, ValuePointerRef,
};
use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

#[cfg(feature = "actix-web")]
pub mod actix_web;
// #[cfg(feature = "axum")]
Copy link
Member

@irevoire irevoire Feb 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should not be commented 😁

Suggested change
// #[cfg(feature = "axum")]
#[cfg(feature = "axum")]

pub mod axum;
mod impls;
mod json;
mod query_params;
Expand Down
4 changes: 2 additions & 2 deletions src/serde_cs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::str::FromStr;
use serde_cs::vec::CS;

use crate::{
take_cf_content, DeserializeError, Deserr, ErrorKind, IntoValue, Value,
ValueKind, ValuePointerRef,
take_cf_content, DeserializeError, Deserr, ErrorKind, IntoValue, Value, ValueKind,
ValuePointerRef,
};

impl<R, E, FE> Deserr<E> for CS<R>
Expand Down
9 changes: 3 additions & 6 deletions tests/attributes/from.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ fn from_container_attribute() {
)
"###);

let data = deserialize::<AsciiString, _, JsonError>(json!("🥺"))
.unwrap();
let data = deserialize::<AsciiString, _, JsonError>(json!("🥺")).unwrap();

assert_debug_snapshot!(data, @r###"
Invalid(
Expand All @@ -56,8 +55,7 @@ fn from_container_attribute() {
}
"###);

let data = deserialize::<Struct, _, JsonError>(json!({ "doggo": "👉 👈"}))
.unwrap();
let data = deserialize::<Struct, _, JsonError>(json!({ "doggo": "👉 👈"})).unwrap();

assert_debug_snapshot!(data, @r###"
Struct {
Expand Down Expand Up @@ -104,8 +102,7 @@ fn from_field_attribute() {
}
"###);

let data = deserialize::<Struct, _, JsonError>(json!({ "doggo": "👉 👈"}))
.unwrap();
let data = deserialize::<Struct, _, JsonError>(json!({ "doggo": "👉 👈"})).unwrap();

assert_debug_snapshot!(data, @r###"
Struct {
Expand Down
9 changes: 3 additions & 6 deletions tests/attributes/try_from.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ fn from_container_attribute() {
)
"###);

let data = deserialize::<AsciiString, _, JsonError>(json!("🥺"))
.unwrap_err();
let data = deserialize::<AsciiString, _, JsonError>(json!("🥺")).unwrap_err();

assert_display_snapshot!(data, @"Invalid value: Encountered invalid character: `🥺`, only ascii characters are accepted");

Expand All @@ -92,8 +91,7 @@ fn from_container_attribute() {
}
"###);

let data = deserialize::<Struct, _, JsonError>(json!({ "doggo": "👉 👈"}))
.unwrap_err();
let data = deserialize::<Struct, _, JsonError>(json!({ "doggo": "👉 👈"})).unwrap_err();

assert_display_snapshot!(data, @"Invalid value at `.doggo`: Encountered invalid character: `👉`, only ascii characters are accepted");
}
Expand Down Expand Up @@ -133,8 +131,7 @@ fn from_field_attribute() {
}
"###);

let data = deserialize::<Struct, _, JsonError>(json!({ "doggo": "👉 👈"}))
.unwrap_err();
let data = deserialize::<Struct, _, JsonError>(json!({ "doggo": "👉 👈"})).unwrap_err();

assert_display_snapshot!(data, @"Invalid value at `.doggo`: Encountered invalid character: `👉`, only ascii characters are accepted");
}