1
0
Fork 0
mirror of https://gitlab.com/msrd0/gotham-restful.git synced 2025-04-19 22:44:38 +00:00
deprecated-gotham-restful/gotham_restful/src/result.rs

313 lines
6.4 KiB
Rust
Raw Normal View History

2019-09-30 20:58:15 +02:00
use crate::{ResourceType, StatusCode};
2019-10-01 00:23:34 +02:00
#[cfg(feature = "openapi")]
2019-10-05 14:50:05 +02:00
use crate::{OpenapiSchema, OpenapiType};
2019-10-19 20:06:30 +02:00
use mime::{Mime, APPLICATION_JSON};
2019-09-26 17:24:40 +02:00
use serde::Serialize;
2019-09-27 15:35:02 +02:00
use serde_json::error::Error as SerdeJsonError;
2019-09-26 17:24:40 +02:00
use std::error::Error;
pub struct Response
{
pub status : StatusCode,
pub body : String,
pub mime : Option<Mime>
}
impl Response
{
pub fn json(status : StatusCode, body : String) -> Self
{
Self {
status,
body,
mime: Some(APPLICATION_JSON)
}
}
pub fn no_content() -> Self
{
Self {
status: StatusCode::NO_CONTENT,
body: String::new(),
mime: None
}
}
}
2019-09-27 15:35:02 +02:00
/// A trait provided to convert a resource's result to json.
pub trait ResourceResult
2019-09-26 17:24:40 +02:00
{
2019-10-19 20:06:30 +02:00
/// Turn this into a response that can be returned to the browser. This api will likely
/// change in the future.
fn to_response(&self) -> Result<Response, SerdeJsonError>;
2019-10-19 20:06:30 +02:00
/// Return a list of supported mime types.
fn accepted_types() -> Option<Vec<Mime>>
{
None
}
2019-09-30 23:53:55 +02:00
#[cfg(feature = "openapi")]
2019-10-13 23:36:10 +02:00
fn schema() -> OpenapiSchema;
2019-10-05 14:50:05 +02:00
#[cfg(feature = "openapi")]
fn default_status() -> StatusCode
{
StatusCode::OK
}
2019-09-26 17:24:40 +02:00
}
2019-10-01 00:49:13 +02:00
#[cfg(feature = "openapi")]
impl<Res : ResourceResult> crate::OpenapiType for Res
{
2019-10-13 23:36:10 +02:00
fn schema() -> OpenapiSchema
2019-10-01 00:49:13 +02:00
{
2019-10-13 23:36:10 +02:00
Self::schema()
2019-10-01 00:49:13 +02:00
}
}
2019-09-27 15:35:02 +02:00
/// The default json returned on an 500 Internal Server Error.
2019-09-26 17:24:40 +02:00
#[derive(Debug, Serialize)]
pub 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()
}
}
}
2019-09-30 20:58:15 +02:00
impl<R : ResourceType, E : Error> ResourceResult for Result<R, E>
2019-09-26 17:24:40 +02:00
{
fn to_response(&self) -> Result<Response, SerdeJsonError>
2019-09-26 17:24:40 +02:00
{
2019-09-27 15:35:02 +02:00
Ok(match self {
Ok(r) => Response::json(StatusCode::OK, serde_json::to_string(r)?),
2019-09-27 15:35:02 +02:00
Err(e) => {
let err : ResourceError = e.into();
Response::json(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?)
2019-09-27 15:35:02 +02:00
}
})
}
2019-09-30 23:53:55 +02:00
2019-10-19 20:06:30 +02:00
fn accepted_types() -> Option<Vec<Mime>>
{
Some(vec![APPLICATION_JSON])
}
2019-09-30 23:53:55 +02:00
#[cfg(feature = "openapi")]
2019-10-13 23:36:10 +02:00
fn schema() -> OpenapiSchema
2019-09-30 20:58:15 +02:00
{
2019-10-13 23:36:10 +02:00
R::schema()
2019-09-30 20:58:15 +02:00
}
2019-09-27 15:35:02 +02:00
}
2019-10-14 00:59:02 +02:00
/**
This can be returned from a resource when there is no cause of an error. For example:
```
# #[macro_use] extern crate gotham_restful_derive;
# use gotham::state::State;
2019-10-14 02:37:50 +02:00
# use gotham_restful::*;
2019-10-14 00:59:02 +02:00
# use serde::{Deserialize, Serialize};
#
# #[derive(Resource)]
# struct MyResource;
#
#[derive(Deserialize, Serialize)]
# #[derive(OpenapiType)]
struct MyResponse {
message: String
}
#[rest_read_all(MyResource)]
fn read_all(_state: &mut State) -> Success<MyResponse> {
let res = MyResponse { message: "I'm always happy".to_string() };
res.into()
}
```
*/
2019-09-27 15:35:02 +02:00
pub struct Success<T>(T);
impl<T> From<T> for Success<T>
{
fn from(t : T) -> Self
{
Self(t)
}
}
2019-09-30 20:58:15 +02:00
impl<T : ResourceType> ResourceResult for Success<T>
2019-09-27 15:35:02 +02:00
{
fn to_response(&self) -> Result<Response, SerdeJsonError>
2019-09-27 15:35:02 +02:00
{
Ok(Response::json(StatusCode::OK, serde_json::to_string(&self.0)?))
2019-09-26 17:24:40 +02:00
}
2019-09-30 23:53:55 +02:00
2019-10-19 20:06:30 +02:00
fn accepted_types() -> Option<Vec<Mime>>
{
Some(vec![APPLICATION_JSON])
}
2019-09-30 23:53:55 +02:00
#[cfg(feature = "openapi")]
2019-10-13 23:36:10 +02:00
fn schema() -> OpenapiSchema
2019-09-30 20:58:15 +02:00
{
2019-10-13 23:36:10 +02:00
T::schema()
2019-09-30 20:58:15 +02:00
}
2019-09-26 17:24:40 +02:00
}
2019-10-05 14:50:05 +02:00
2019-10-14 00:59:02 +02:00
/**
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;
# use gotham::state::State;
2019-10-14 02:37:50 +02:00
# use gotham_restful::*;
2019-10-14 00:59:02 +02:00
#
# #[derive(Resource)]
# struct MyResource;
#
#[rest_read_all(MyResource)]
fn read_all(_state: &mut State) {
// do something
}
```
*/
2019-10-13 23:36:10 +02:00
#[derive(Default)]
2019-10-05 14:50:05 +02:00
pub struct NoContent;
impl From<()> for NoContent
{
fn from(_ : ()) -> Self
{
Self {}
}
}
impl ResourceResult for NoContent
{
2019-10-14 00:59:02 +02:00
/// This will always be a _204 No Content_ together with an empty string.
fn to_response(&self) -> Result<Response, SerdeJsonError>
2019-10-05 14:50:05 +02:00
{
Ok(Response::no_content())
2019-10-05 14:50:05 +02:00
}
2019-10-14 00:59:02 +02:00
/// Returns the schema of the `()` type.
2019-10-05 14:50:05 +02:00
#[cfg(feature = "openapi")]
2019-10-13 23:36:10 +02:00
fn schema() -> OpenapiSchema
2019-10-05 14:50:05 +02:00
{
2019-10-13 23:36:10 +02:00
<()>::schema()
2019-10-05 14:50:05 +02:00
}
2019-10-14 00:59:02 +02:00
/// This will always be a _204 No Content_
2019-10-05 14:50:05 +02:00
#[cfg(feature = "openapi")]
fn default_status() -> StatusCode
{
StatusCode::NO_CONTENT
}
}
2019-10-05 16:06:08 +02:00
impl<E : Error> ResourceResult for Result<NoContent, E>
{
fn to_response(&self) -> Result<Response, SerdeJsonError>
2019-10-05 16:06:08 +02:00
{
match self {
Ok(nc) => nc.to_response(),
2019-10-05 16:06:08 +02:00
Err(e) => {
let err : ResourceError = e.into();
Ok(Response::json(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?))
2019-10-05 16:06:08 +02:00
}
}
2019-10-05 16:06:08 +02:00
}
#[cfg(feature = "openapi")]
2019-10-13 23:36:10 +02:00
fn schema() -> OpenapiSchema
2019-10-05 16:06:08 +02:00
{
2019-10-14 02:17:25 +02:00
<NoContent as ResourceResult>::schema()
2019-10-05 16:06:08 +02:00
}
#[cfg(feature = "openapi")]
fn default_status() -> StatusCode
{
2019-10-14 02:17:25 +02:00
NoContent::default_status()
}
}
#[cfg(test)]
mod test
{
use super::*;
use thiserror::Error;
#[derive(Debug, Default, Deserialize, Serialize)]
#[cfg_attr(feature = "openapi", derive(OpenapiType))]
struct Msg
{
msg : String
}
#[derive(Debug, Default, Error)]
#[error("An Error")]
struct MsgError;
#[test]
fn resource_result_ok()
{
let ok : Result<Msg, MsgError> = Ok(Msg::default());
let res = ok.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
assert_eq!(res.body, r#"{"msg":""}"#);
assert_eq!(res.mime, Some(APPLICATION_JSON));
2019-10-14 02:17:25 +02:00
}
#[test]
fn resource_result_err()
{
let err : Result<Msg, MsgError> = Err(MsgError::default());
let res = err.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(res.body, format!(r#"{{"error":true,"message":"{}"}}"#, err.unwrap_err()));
assert_eq!(res.mime, Some(APPLICATION_JSON));
2019-10-14 02:17:25 +02:00
}
#[test]
fn success_always_successfull()
{
let success : Success<Msg> = Msg::default().into();
let res = success.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::OK);
assert_eq!(res.body, r#"{"msg":""}"#);
assert_eq!(res.mime, Some(APPLICATION_JSON));
2019-10-14 02:17:25 +02:00
}
#[test]
fn no_content_has_empty_response()
2019-10-14 02:17:25 +02:00
{
let no_content = NoContent::default();
let res = no_content.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::NO_CONTENT);
assert_eq!(res.body, "");
assert_eq!(res.mime, None);
2019-10-14 02:17:25 +02:00
}
#[test]
fn no_content_result()
{
let no_content : Result<NoContent, MsgError> = Ok(NoContent::default());
let res = no_content.to_response().expect("didn't expect error response");
assert_eq!(res.status, StatusCode::NO_CONTENT);
assert_eq!(res.body, "");
assert_eq!(res.mime, None);
2019-10-05 16:06:08 +02:00
}
}