From 1c59f85ea8b6e64e5e43d9fe49c07a84806ef079 Mon Sep 17 00:00:00 2001 From: Conrad Ludgate Date: Fri, 7 May 2021 21:06:56 +0100 Subject: remove dyn Reply (#48) * cleanup reply types * cleanup error api * small update * improve api some more * fmt --- atuin-common/src/api.rs | 65 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 59 insertions(+), 6 deletions(-) (limited to 'atuin-common') diff --git a/atuin-common/src/api.rs b/atuin-common/src/api.rs index 82ee6604..44a73c1c 100644 --- a/atuin-common/src/api.rs +++ b/atuin-common/src/api.rs @@ -1,4 +1,8 @@ +use std::convert::Infallible; + use chrono::Utc; +use serde::Serialize; +use warp::{reply::Response, Reply}; #[derive(Debug, Serialize, Deserialize)] pub struct UserResponse { @@ -58,13 +62,62 @@ pub struct ErrorResponse { pub reason: String, } +impl Reply for ErrorResponse { + fn into_response(self) -> Response { + warp::reply::json(&self).into_response() + } +} + +pub struct ErrorResponseStatus { + pub error: ErrorResponse, + pub status: warp::http::StatusCode, +} + +impl Reply for ErrorResponseStatus { + fn into_response(self) -> Response { + warp::reply::with_status(self.error, self.status).into_response() + } +} + impl ErrorResponse { - pub fn reply(reason: &str, status: warp::http::StatusCode) -> impl warp::Reply { - warp::reply::with_status( - warp::reply::json(&ErrorResponse { - reason: String::from(reason), - }), + pub fn with_status(self, status: warp::http::StatusCode) -> ErrorResponseStatus { + ErrorResponseStatus { + error: self, status, - ) + } + } + + pub fn reply(reason: &str) -> ErrorResponse { + Self { + reason: reason.to_string(), + } } } + +pub enum ReplyEither { + Ok(T), + Err(E), +} + +impl Reply for ReplyEither { + fn into_response(self) -> Response { + match self { + ReplyEither::Ok(t) => t.into_response(), + ReplyEither::Err(e) => e.into_response(), + } + } +} + +pub type ReplyResult = Result, Infallible>; +pub fn reply_error(e: E) -> ReplyResult { + Ok(ReplyEither::Err(e)) +} + +pub type JSONResult = Result, Infallible>; +pub fn reply_json(t: impl Serialize) -> JSONResult { + reply(warp::reply::json(&t)) +} + +pub fn reply(t: T) -> ReplyResult { + Ok(ReplyEither::Ok(t)) +} -- cgit v1.2.3