Skip to content

Commit

Permalink
feat: salvo_oapi::ToSchema OOTB support for Result<T, E> #427
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn authored Sep 21, 2023
1 parent 6c3c66e commit 373d13a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 24 deletions.
17 changes: 17 additions & 0 deletions crates/oapi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ use std::marker::PhantomData;
use salvo_core::http::StatusError;
use salvo_core::{extract::Extractible, writing};

use crate::oapi::openapi::schema::OneOf;

// https://github.com/bkchr/proc-macro-crate/issues/10
extern crate self as salvo_oapi;

Expand Down Expand Up @@ -302,6 +304,21 @@ impl ToSchema for salvo_core::Error {
}
}

impl<T, E> ToSchema for Result<T, E>
where
T: ToSchema,
E: ToSchema,
{
fn to_schema(components: &mut Components) -> RefOr<schema::Schema> {
let symbol = std::any::type_name::<Self>().replace("::", ".");
let schema = OneOf::new()
.item(T::to_schema(components))
.item(E::to_schema(components));
components.schemas.insert(symbol.clone(), schema.into());
crate::RefOr::Ref(crate::Ref::new(format!("#/components/schemas/{}", symbol)))
}
}

/// Trait used to convert implementing type to OpenAPI parameters.
///
/// This trait is [derivable][derive] for structs which are used to describe `path` or `query` parameters.
Expand Down
41 changes: 17 additions & 24 deletions examples/oapi-todos/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
use once_cell::sync::Lazy;
use salvo::oapi::extract::*;
use salvo::oapi::{extract::*, ToSchema};
use salvo::prelude::*;

use self::models::*;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;

static STORE: Lazy<Db> = Lazy::new(new_store);
pub type Db = Mutex<Vec<Todo>>;

pub fn new_store() -> Db {
Mutex::new(Vec::new())
}

#[derive(Serialize, Deserialize, Clone, Debug, ToSchema)]
pub struct Todo {
#[salvo(schema(example = 1))]
pub id: u64,
#[salvo(schema(example = "Buy coffee"))]
pub text: String,
pub completed: bool,
}

#[tokio::main]
async fn main() {
Expand Down Expand Up @@ -108,27 +122,6 @@ pub async fn delete_todo(id: PathParam<u64>) -> Result<StatusCode, StatusError>
}
}

mod models {
use salvo::oapi::ToSchema;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;

pub type Db = Mutex<Vec<Todo>>;

pub fn new_store() -> Db {
Mutex::new(Vec::new())
}

#[derive(Serialize, Deserialize, Clone, Debug, ToSchema)]
pub struct Todo {
#[salvo(schema(example = 1))]
pub id: u64,
#[salvo(schema(example = "Buy coffee"))]
pub text: String,
pub completed: bool,
}
}

static INDEX_HTML: &str = r#"<!DOCTYPE html>
<html>
<head>
Expand Down

0 comments on commit 373d13a

Please sign in to comment.