mirror of
https://gitlab.com/msrd0/gotham-restful.git
synced 2025-04-20 06:54:46 +00:00
merge workspace and main crate
This commit is contained in:
parent
52679ad29d
commit
5587ded60d
45 changed files with 58 additions and 67 deletions
109
src/result/auth_result.rs
Normal file
109
src/result/auth_result.rs
Normal file
|
@ -0,0 +1,109 @@
|
|||
use gotham_restful_derive::ResourceError;
|
||||
|
||||
|
||||
/**
|
||||
This is an error type that always yields a _403 Forbidden_ response. This type is best used in
|
||||
combination with [`AuthSuccess`] or [`AuthResult`].
|
||||
|
||||
[`AuthSuccess`]: type.AuthSuccess.html
|
||||
[`AuthResult`]: type.AuthResult.html
|
||||
*/
|
||||
#[derive(Debug, Clone, Copy, ResourceError)]
|
||||
pub enum AuthError
|
||||
{
|
||||
#[status(FORBIDDEN)]
|
||||
#[display("Forbidden")]
|
||||
Forbidden
|
||||
}
|
||||
|
||||
/**
|
||||
This return type can be used to map another `ResourceResult` that can only be returned if the
|
||||
client is authenticated. Otherwise, an empty _403 Forbidden_ response will be issued. Use can
|
||||
look something like this (assuming the `auth` feature is enabled):
|
||||
|
||||
```
|
||||
# #[macro_use] extern crate gotham_restful_derive;
|
||||
# mod doc_tests_are_broken {
|
||||
# use gotham::state::State;
|
||||
# use gotham_restful::*;
|
||||
# use serde::Deserialize;
|
||||
#
|
||||
# #[derive(Resource)]
|
||||
# #[resource(read_all)]
|
||||
# struct MyResource;
|
||||
#
|
||||
# #[derive(Clone, Deserialize)]
|
||||
# struct MyAuthData { exp : u64 }
|
||||
#
|
||||
#[read_all(MyResource)]
|
||||
fn read_all(auth : AuthStatus<MyAuthData>) -> AuthSuccess<NoContent> {
|
||||
let auth_data = match auth {
|
||||
AuthStatus::Authenticated(data) => data,
|
||||
_ => return Err(Forbidden)
|
||||
};
|
||||
// do something
|
||||
Ok(NoContent::default())
|
||||
}
|
||||
# }
|
||||
```
|
||||
*/
|
||||
pub type AuthSuccess<T> = Result<T, AuthError>;
|
||||
|
||||
/**
|
||||
This is an error type that either yields a _403 Forbidden_ respone if produced from an authentication
|
||||
error, or delegates to another error type. This type is best used with [`AuthResult`].
|
||||
|
||||
[`AuthResult`]: type.AuthResult.html
|
||||
*/
|
||||
#[derive(Debug, ResourceError)]
|
||||
pub enum AuthErrorOrOther<E>
|
||||
{
|
||||
#[status(UNAUTHORIZED)]
|
||||
#[display("Forbidden")]
|
||||
Forbidden,
|
||||
#[display("{0}")]
|
||||
Other(#[from] E)
|
||||
}
|
||||
|
||||
impl<E> From<AuthError> for AuthErrorOrOther<E>
|
||||
{
|
||||
fn from(err : AuthError) -> Self
|
||||
{
|
||||
match err {
|
||||
AuthError::Forbidden => Self::Forbidden
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
This return type can be used to map another `ResourceResult` that can only be returned if the
|
||||
client is authenticated. Otherwise, an empty _403 Forbidden_ response will be issued. Use can
|
||||
look something like this (assuming the `auth` feature is enabled):
|
||||
|
||||
```
|
||||
# #[macro_use] extern crate gotham_restful_derive;
|
||||
# mod doc_tests_are_broken {
|
||||
# use gotham::state::State;
|
||||
# use gotham_restful::*;
|
||||
# use serde::Deserialize;
|
||||
# use std::io;
|
||||
#
|
||||
# #[derive(Resource)]
|
||||
# #[resource(read_all)]
|
||||
# struct MyResource;
|
||||
#
|
||||
# #[derive(Clone, Deserialize)]
|
||||
# struct MyAuthData { exp : u64 }
|
||||
#
|
||||
#[read_all(MyResource)]
|
||||
fn read_all(auth : AuthStatus<MyAuthData>) -> AuthResult<NoContent, io::Error> {
|
||||
let auth_data = match auth {
|
||||
AuthStatus::Authenticated(data) => data,
|
||||
_ => Err(Forbidden)?
|
||||
};
|
||||
// do something
|
||||
Ok(NoContent::default().into())
|
||||
}
|
||||
# }
|
||||
*/
|
||||
pub type AuthResult<T, E> = Result<T, AuthErrorOrOther<E>>;
|
191
src/result/mod.rs
Normal file
191
src/result/mod.rs
Normal file
|
@ -0,0 +1,191 @@
|
|||
use crate::Response;
|
||||
#[cfg(feature = "openapi")]
|
||||
use crate::OpenapiSchema;
|
||||
use futures_util::future::FutureExt;
|
||||
use mime::{Mime, STAR_STAR};
|
||||
use serde::Serialize;
|
||||
use std::{
|
||||
error::Error,
|
||||
future::Future,
|
||||
fmt::{Debug, Display},
|
||||
pin::Pin
|
||||
};
|
||||
|
||||
mod auth_result;
|
||||
pub use auth_result::{AuthError, AuthErrorOrOther, AuthResult, AuthSuccess};
|
||||
|
||||
mod no_content;
|
||||
pub use no_content::NoContent;
|
||||
|
||||
mod raw;
|
||||
pub use raw::Raw;
|
||||
|
||||
#[allow(clippy::module_inception)]
|
||||
mod result;
|
||||
pub use result::IntoResponseError;
|
||||
|
||||
mod success;
|
||||
pub use success::Success;
|
||||
|
||||
|
||||
pub(crate) trait OrAllTypes
|
||||
{
|
||||
fn or_all_types(self) -> Vec<Mime>;
|
||||
}
|
||||
|
||||
impl OrAllTypes for Option<Vec<Mime>>
|
||||
{
|
||||
fn or_all_types(self) -> Vec<Mime>
|
||||
{
|
||||
self.unwrap_or_else(|| vec![STAR_STAR])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// A trait provided to convert a resource's result to json.
|
||||
pub trait ResourceResult
|
||||
{
|
||||
type Err : Error + Send + 'static;
|
||||
|
||||
/// Turn this into a response that can be returned to the browser. This api will likely
|
||||
/// change in the future.
|
||||
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>>;
|
||||
|
||||
/// Return a list of supported mime types.
|
||||
fn accepted_types() -> Option<Vec<Mime>>
|
||||
{
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn schema() -> OpenapiSchema;
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn default_status() -> crate::StatusCode
|
||||
{
|
||||
crate::StatusCode::OK
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
impl<Res : ResourceResult> crate::OpenapiType for Res
|
||||
{
|
||||
fn schema() -> OpenapiSchema
|
||||
{
|
||||
Self::schema()
|
||||
}
|
||||
}
|
||||
|
||||
/// The default json returned on an 500 Internal Server Error.
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(crate) struct ResourceError
|
||||
{
|
||||
error : bool,
|
||||
message : String
|
||||
}
|
||||
|
||||
impl<T : ToString> From<T> for ResourceError
|
||||
{
|
||||
fn from(message : T) -> Self
|
||||
{
|
||||
Self {
|
||||
error: true,
|
||||
message: message.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn into_response_helper<Err, F>(create_response : F) -> Pin<Box<dyn Future<Output = Result<Response, Err>> + Send>>
|
||||
where
|
||||
Err : Send + 'static,
|
||||
F : FnOnce() -> Result<Response, Err>
|
||||
{
|
||||
let res = create_response();
|
||||
async move { res }.boxed()
|
||||
}
|
||||
|
||||
#[cfg(feature = "errorlog")]
|
||||
fn errorlog<E : Display>(e : E)
|
||||
{
|
||||
error!("The handler encountered an error: {}", e);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "errorlog"))]
|
||||
fn errorlog<E>(_e : E) {}
|
||||
|
||||
fn handle_error<E>(e : E) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>>
|
||||
where
|
||||
E : Display + IntoResponseError
|
||||
{
|
||||
into_response_helper(|| {
|
||||
errorlog(&e);
|
||||
e.into_response_error()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
impl<Res> ResourceResult for Pin<Box<dyn Future<Output = Res> + Send>>
|
||||
where
|
||||
Res : ResourceResult + 'static
|
||||
{
|
||||
type Err = Res::Err;
|
||||
|
||||
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>>
|
||||
{
|
||||
self.then(|result| {
|
||||
result.into_response()
|
||||
}).boxed()
|
||||
}
|
||||
|
||||
fn accepted_types() -> Option<Vec<Mime>>
|
||||
{
|
||||
Res::accepted_types()
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn schema() -> OpenapiSchema
|
||||
{
|
||||
Res::schema()
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn default_status() -> crate::StatusCode
|
||||
{
|
||||
Res::default_status()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test
|
||||
{
|
||||
use super::*;
|
||||
use futures_executor::block_on;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
#[cfg_attr(feature = "openapi", derive(crate::OpenapiType))]
|
||||
struct Msg
|
||||
{
|
||||
msg : String
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Error)]
|
||||
#[error("An Error")]
|
||||
struct MsgError;
|
||||
|
||||
#[test]
|
||||
fn result_from_future()
|
||||
{
|
||||
let nc = NoContent::default();
|
||||
let res = block_on(nc.into_response()).unwrap();
|
||||
|
||||
let fut_nc = async move { NoContent::default() }.boxed();
|
||||
let fut_res = block_on(fut_nc.into_response()).unwrap();
|
||||
|
||||
assert_eq!(res.status, fut_res.status);
|
||||
assert_eq!(res.mime, fut_res.mime);
|
||||
assert_eq!(res.full_body().unwrap(), fut_res.full_body().unwrap());
|
||||
}
|
||||
}
|
141
src/result/no_content.rs
Normal file
141
src/result/no_content.rs
Normal file
|
@ -0,0 +1,141 @@
|
|||
use super::{ResourceResult, handle_error};
|
||||
use crate::{IntoResponseError, Response};
|
||||
#[cfg(feature = "openapi")]
|
||||
use crate::{OpenapiSchema, OpenapiType};
|
||||
use futures_util::{future, future::FutureExt};
|
||||
use mime::Mime;
|
||||
use std::{
|
||||
fmt::Display,
|
||||
future::Future,
|
||||
pin::Pin
|
||||
};
|
||||
|
||||
/**
|
||||
This is the return type of a resource that doesn't actually return something. It will result
|
||||
in a _204 No Content_ answer by default. You don't need to use this type directly if using
|
||||
the function attributes:
|
||||
|
||||
```
|
||||
# #[macro_use] extern crate gotham_restful_derive;
|
||||
# mod doc_tests_are_broken {
|
||||
# use gotham::state::State;
|
||||
# use gotham_restful::*;
|
||||
#
|
||||
# #[derive(Resource)]
|
||||
# #[resource(read_all)]
|
||||
# struct MyResource;
|
||||
#
|
||||
#[read_all(MyResource)]
|
||||
fn read_all(_state: &mut State) {
|
||||
// do something
|
||||
}
|
||||
# }
|
||||
```
|
||||
*/
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct NoContent;
|
||||
|
||||
impl From<()> for NoContent
|
||||
{
|
||||
fn from(_ : ()) -> Self
|
||||
{
|
||||
Self {}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourceResult for NoContent
|
||||
{
|
||||
// TODO this shouldn't be a serde_json::Error
|
||||
type Err = serde_json::Error; // just for easier handling of `Result<NoContent, E>`
|
||||
|
||||
/// This will always be a _204 No Content_ together with an empty string.
|
||||
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>>
|
||||
{
|
||||
future::ok(Response::no_content()).boxed()
|
||||
}
|
||||
|
||||
fn accepted_types() -> Option<Vec<Mime>>
|
||||
{
|
||||
Some(Vec::new())
|
||||
}
|
||||
|
||||
/// Returns the schema of the `()` type.
|
||||
#[cfg(feature = "openapi")]
|
||||
fn schema() -> OpenapiSchema
|
||||
{
|
||||
<()>::schema()
|
||||
}
|
||||
|
||||
/// This will always be a _204 No Content_
|
||||
#[cfg(feature = "openapi")]
|
||||
fn default_status() -> crate::StatusCode
|
||||
{
|
||||
crate::StatusCode::NO_CONTENT
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> ResourceResult for Result<NoContent, E>
|
||||
where
|
||||
E : Display + IntoResponseError<Err = serde_json::Error>
|
||||
{
|
||||
type Err = serde_json::Error;
|
||||
|
||||
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, serde_json::Error>> + Send>>
|
||||
{
|
||||
match self {
|
||||
Ok(nc) => nc.into_response(),
|
||||
Err(e) => handle_error(e)
|
||||
}
|
||||
}
|
||||
|
||||
fn accepted_types() -> Option<Vec<Mime>>
|
||||
{
|
||||
NoContent::accepted_types()
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn schema() -> OpenapiSchema
|
||||
{
|
||||
<NoContent as ResourceResult>::schema()
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn default_status() -> crate::StatusCode
|
||||
{
|
||||
NoContent::default_status()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test
|
||||
{
|
||||
use super::*;
|
||||
use futures_executor::block_on;
|
||||
use gotham::hyper::StatusCode;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Default, Error)]
|
||||
#[error("An Error")]
|
||||
struct MsgError;
|
||||
|
||||
#[test]
|
||||
fn no_content_has_empty_response()
|
||||
{
|
||||
let no_content = NoContent::default();
|
||||
let res = block_on(no_content.into_response()).expect("didn't expect error response");
|
||||
assert_eq!(res.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(res.mime, None);
|
||||
assert_eq!(res.full_body().unwrap(), &[] as &[u8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_content_result()
|
||||
{
|
||||
let no_content : Result<NoContent, MsgError> = Ok(NoContent::default());
|
||||
let res = block_on(no_content.into_response()).expect("didn't expect error response");
|
||||
assert_eq!(res.status, StatusCode::NO_CONTENT);
|
||||
assert_eq!(res.mime, None);
|
||||
assert_eq!(res.full_body().unwrap(), &[] as &[u8]);
|
||||
}
|
||||
}
|
168
src/result/raw.rs
Normal file
168
src/result/raw.rs
Normal file
|
@ -0,0 +1,168 @@
|
|||
use super::{IntoResponseError, ResourceResult, handle_error};
|
||||
use crate::{FromBody, RequestBody, ResourceType, Response, StatusCode};
|
||||
#[cfg(feature = "openapi")]
|
||||
use crate::OpenapiSchema;
|
||||
use futures_core::future::Future;
|
||||
use futures_util::{future, future::FutureExt};
|
||||
use gotham::hyper::body::{Body, Bytes};
|
||||
use mime::Mime;
|
||||
#[cfg(feature = "openapi")]
|
||||
use openapiv3::{SchemaKind, StringFormat, StringType, Type, VariantOrUnknownOrEmpty};
|
||||
use serde_json::error::Error as SerdeJsonError;
|
||||
use std::{
|
||||
convert::Infallible,
|
||||
fmt::Display,
|
||||
pin::Pin
|
||||
};
|
||||
|
||||
/**
|
||||
This type can be used both as a raw request body, as well as as a raw response. However, all types
|
||||
of request bodies are accepted by this type. It is therefore recommended to derive your own type
|
||||
from [`RequestBody`] and only use this when you need to return a raw response. This is a usage
|
||||
example that simply returns its body:
|
||||
|
||||
```rust,no_run
|
||||
# #[macro_use] extern crate gotham_restful_derive;
|
||||
# use gotham::router::builder::*;
|
||||
# use gotham_restful::*;
|
||||
#[derive(Resource)]
|
||||
#[resource(create)]
|
||||
struct ImageResource;
|
||||
|
||||
#[create(ImageResource)]
|
||||
fn create(body : Raw<Vec<u8>>) -> Raw<Vec<u8>> {
|
||||
body
|
||||
}
|
||||
# fn main() {
|
||||
# gotham::start("127.0.0.1:8080", build_simple_router(|route| {
|
||||
# route.resource::<ImageResource>("img");
|
||||
# }));
|
||||
# }
|
||||
```
|
||||
|
||||
[`OpenapiType`]: trait.OpenapiType.html
|
||||
*/
|
||||
#[derive(Debug)]
|
||||
pub struct Raw<T>
|
||||
{
|
||||
pub raw : T,
|
||||
pub mime : Mime
|
||||
}
|
||||
|
||||
impl<T> Raw<T>
|
||||
{
|
||||
pub fn new(raw : T, mime : Mime) -> Self
|
||||
{
|
||||
Self { raw, mime }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> AsMut<U> for Raw<T>
|
||||
where
|
||||
T : AsMut<U>
|
||||
{
|
||||
fn as_mut(&mut self) -> &mut U
|
||||
{
|
||||
self.raw.as_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> AsRef<U> for Raw<T>
|
||||
where
|
||||
T : AsRef<U>
|
||||
{
|
||||
fn as_ref(&self) -> &U
|
||||
{
|
||||
self.raw.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T : Clone> Clone for Raw<T>
|
||||
{
|
||||
fn clone(&self) -> Self
|
||||
{
|
||||
Self {
|
||||
raw: self.raw.clone(),
|
||||
mime: self.mime.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T : for<'a> From<&'a [u8]>> FromBody for Raw<T>
|
||||
{
|
||||
type Err = Infallible;
|
||||
|
||||
fn from_body(body : Bytes, mime : Mime) -> Result<Self, Self::Err>
|
||||
{
|
||||
Ok(Self::new(body.as_ref().into(), mime))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> RequestBody for Raw<T>
|
||||
where
|
||||
Raw<T> : FromBody + ResourceType
|
||||
{
|
||||
}
|
||||
|
||||
impl<T : Into<Body>> ResourceResult for Raw<T>
|
||||
where
|
||||
Self : Send
|
||||
{
|
||||
type Err = SerdeJsonError; // just for easier handling of `Result<Raw<T>, E>`
|
||||
|
||||
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, SerdeJsonError>> + Send>>
|
||||
{
|
||||
future::ok(Response::new(StatusCode::OK, self.raw, Some(self.mime.clone()))).boxed()
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn schema() -> OpenapiSchema
|
||||
{
|
||||
OpenapiSchema::new(SchemaKind::Type(Type::String(StringType {
|
||||
format: VariantOrUnknownOrEmpty::Item(StringFormat::Binary),
|
||||
..Default::default()
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> ResourceResult for Result<Raw<T>, E>
|
||||
where
|
||||
Raw<T> : ResourceResult,
|
||||
E : Display + IntoResponseError<Err = <Raw<T> as ResourceResult>::Err>
|
||||
{
|
||||
type Err = E::Err;
|
||||
|
||||
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>>
|
||||
{
|
||||
match self {
|
||||
Ok(raw) => raw.into_response(),
|
||||
Err(e) => handle_error(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn schema() -> OpenapiSchema
|
||||
{
|
||||
<Raw<T> as ResourceResult>::schema()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test
|
||||
{
|
||||
use super::*;
|
||||
use futures_executor::block_on;
|
||||
use mime::TEXT_PLAIN;
|
||||
|
||||
#[test]
|
||||
fn raw_response()
|
||||
{
|
||||
let msg = "Test";
|
||||
let raw = Raw::new(msg, TEXT_PLAIN);
|
||||
let res = block_on(raw.into_response()).expect("didn't expect error response");
|
||||
assert_eq!(res.status, StatusCode::OK);
|
||||
assert_eq!(res.mime, Some(TEXT_PLAIN));
|
||||
assert_eq!(res.full_body().unwrap(), msg.as_bytes());
|
||||
}
|
||||
}
|
106
src/result/result.rs
Normal file
106
src/result/result.rs
Normal file
|
@ -0,0 +1,106 @@
|
|||
use super::{ResourceResult, handle_error, into_response_helper};
|
||||
use crate::{
|
||||
result::ResourceError,
|
||||
Response, ResponseBody, StatusCode
|
||||
};
|
||||
#[cfg(feature = "openapi")]
|
||||
use crate::OpenapiSchema;
|
||||
use futures_core::future::Future;
|
||||
use mime::{Mime, APPLICATION_JSON};
|
||||
use std::{
|
||||
error::Error,
|
||||
fmt::Display,
|
||||
pin::Pin
|
||||
};
|
||||
|
||||
pub trait IntoResponseError
|
||||
{
|
||||
type Err : Error + Send + 'static;
|
||||
|
||||
fn into_response_error(self) -> Result<Response, Self::Err>;
|
||||
}
|
||||
|
||||
impl<E : Error> IntoResponseError for E
|
||||
{
|
||||
type Err = serde_json::Error;
|
||||
|
||||
fn into_response_error(self) -> Result<Response, Self::Err>
|
||||
{
|
||||
let err : ResourceError = self.into();
|
||||
Ok(Response::json(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E> ResourceResult for Result<R, E>
|
||||
where
|
||||
R : ResponseBody,
|
||||
E : Display + IntoResponseError<Err = serde_json::Error>
|
||||
{
|
||||
type Err = E::Err;
|
||||
|
||||
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, E::Err>> + Send>>
|
||||
{
|
||||
match self {
|
||||
Ok(r) => into_response_helper(|| Ok(Response::json(StatusCode::OK, serde_json::to_string(&r)?))),
|
||||
Err(e) => handle_error(e)
|
||||
}
|
||||
}
|
||||
|
||||
fn accepted_types() -> Option<Vec<Mime>>
|
||||
{
|
||||
Some(vec![APPLICATION_JSON])
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn schema() -> OpenapiSchema
|
||||
{
|
||||
R::schema()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test
|
||||
{
|
||||
use super::*;
|
||||
use crate::result::OrAllTypes;
|
||||
use futures_executor::block_on;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
#[cfg_attr(feature = "openapi", derive(crate::OpenapiType))]
|
||||
struct Msg
|
||||
{
|
||||
msg : String
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Error)]
|
||||
#[error("An Error")]
|
||||
struct MsgError;
|
||||
|
||||
#[test]
|
||||
fn result_ok()
|
||||
{
|
||||
let ok : Result<Msg, MsgError> = Ok(Msg::default());
|
||||
let res = block_on(ok.into_response()).expect("didn't expect error response");
|
||||
assert_eq!(res.status, StatusCode::OK);
|
||||
assert_eq!(res.mime, Some(APPLICATION_JSON));
|
||||
assert_eq!(res.full_body().unwrap(), r#"{"msg":""}"#.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn result_err()
|
||||
{
|
||||
let err : Result<Msg, MsgError> = Err(MsgError::default());
|
||||
let res = block_on(err.into_response()).expect("didn't expect error response");
|
||||
assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert_eq!(res.mime, Some(APPLICATION_JSON));
|
||||
assert_eq!(res.full_body().unwrap(), format!(r#"{{"error":true,"message":"{}"}}"#, MsgError::default()).as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_accepts_json()
|
||||
{
|
||||
assert!(<Result<Msg, MsgError>>::accepted_types().or_all_types().contains(&APPLICATION_JSON))
|
||||
}
|
||||
}
|
163
src/result/success.rs
Normal file
163
src/result/success.rs
Normal file
|
@ -0,0 +1,163 @@
|
|||
use super::{ResourceResult, into_response_helper};
|
||||
use crate::{Response, ResponseBody};
|
||||
#[cfg(feature = "openapi")]
|
||||
use crate::OpenapiSchema;
|
||||
use gotham::hyper::StatusCode;
|
||||
use mime::{Mime, APPLICATION_JSON};
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
ops::{Deref, DerefMut}
|
||||
};
|
||||
|
||||
/**
|
||||
This can be returned from a resource when there is no cause of an error. It behaves similar to a
|
||||
smart pointer like box, it that it implements `AsRef`, `Deref` and the likes.
|
||||
|
||||
Usage example:
|
||||
|
||||
```
|
||||
# #[macro_use] extern crate gotham_restful_derive;
|
||||
# mod doc_tests_are_broken {
|
||||
# use gotham::state::State;
|
||||
# use gotham_restful::*;
|
||||
# use serde::{Deserialize, Serialize};
|
||||
#
|
||||
# #[derive(Resource)]
|
||||
# #[resource(read_all)]
|
||||
# struct MyResource;
|
||||
#
|
||||
#[derive(Deserialize, Serialize)]
|
||||
# #[derive(OpenapiType)]
|
||||
struct MyResponse {
|
||||
message: &'static str
|
||||
}
|
||||
|
||||
#[read_all(MyResource)]
|
||||
fn read_all(_state: &mut State) -> Success<MyResponse> {
|
||||
let res = MyResponse { message: "I'm always happy" };
|
||||
res.into()
|
||||
}
|
||||
# }
|
||||
```
|
||||
*/
|
||||
#[derive(Debug)]
|
||||
pub struct Success<T>(T);
|
||||
|
||||
impl<T> AsMut<T> for Success<T>
|
||||
{
|
||||
fn as_mut(&mut self) -> &mut T
|
||||
{
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> AsRef<T> for Success<T>
|
||||
{
|
||||
fn as_ref(&self) -> &T
|
||||
{
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Success<T>
|
||||
{
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T
|
||||
{
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DerefMut for Success<T>
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut T
|
||||
{
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for Success<T>
|
||||
{
|
||||
fn from(t : T) -> Self
|
||||
{
|
||||
Self(t)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T : Clone> Clone for Success<T>
|
||||
{
|
||||
fn clone(&self) -> Self
|
||||
{
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T : Copy> Copy for Success<T>
|
||||
{
|
||||
}
|
||||
|
||||
impl<T : Default> Default for Success<T>
|
||||
{
|
||||
fn default() -> Self
|
||||
{
|
||||
Self(T::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T : ResponseBody> ResourceResult for Success<T>
|
||||
where
|
||||
Self : Send
|
||||
{
|
||||
type Err = serde_json::Error;
|
||||
|
||||
fn into_response(self) -> Pin<Box<dyn Future<Output = Result<Response, Self::Err>> + Send>>
|
||||
{
|
||||
into_response_helper(|| Ok(Response::json(StatusCode::OK, serde_json::to_string(self.as_ref())?)))
|
||||
}
|
||||
|
||||
fn accepted_types() -> Option<Vec<Mime>>
|
||||
{
|
||||
Some(vec![APPLICATION_JSON])
|
||||
}
|
||||
|
||||
#[cfg(feature = "openapi")]
|
||||
fn schema() -> OpenapiSchema
|
||||
{
|
||||
T::schema()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test
|
||||
{
|
||||
use super::*;
|
||||
use crate::result::OrAllTypes;
|
||||
use futures_executor::block_on;
|
||||
|
||||
#[derive(Debug, Default, Serialize)]
|
||||
#[cfg_attr(feature = "openapi", derive(crate::OpenapiType))]
|
||||
struct Msg
|
||||
{
|
||||
msg : String
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_always_successfull()
|
||||
{
|
||||
let success : Success<Msg> = Msg::default().into();
|
||||
let res = block_on(success.into_response()).expect("didn't expect error response");
|
||||
assert_eq!(res.status, StatusCode::OK);
|
||||
assert_eq!(res.mime, Some(APPLICATION_JSON));
|
||||
assert_eq!(res.full_body().unwrap(), r#"{"msg":""}"#.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_accepts_json()
|
||||
{
|
||||
assert!(<Success<Msg>>::accepted_types().or_all_types().contains(&APPLICATION_JSON))
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue