1
Fork 0
mirror of https://github.com/Steffo99/todocolors.git synced 2024-11-22 08:14:18 +00:00

Generalize RedisUnwrapOr500 trait to UnwrapOr500

This commit is contained in:
Steffo 2023-07-31 12:00:12 +02:00
parent a705e73803
commit 3353eea1a0
Signed by: steffo
GPG key ID: 2A24051445686895
2 changed files with 25 additions and 13 deletions

View file

@ -1,7 +1,7 @@
use axum::{Extension, Json}; use axum::{Extension, Json};
use axum::http::StatusCode; use axum::http::StatusCode;
use crate::utils::{RedisConnectOr500, RedisUnwrapOr500, Result}; use crate::utils::{RedisConnectOr500, UnwrapOr500, Result};
const MAJOR: u32 = pkg_version::pkg_version_major!(); const MAJOR: u32 = pkg_version::pkg_version_major!();
const MINOR: u32 = pkg_version::pkg_version_minor!(); const MINOR: u32 = pkg_version::pkg_version_minor!();
@ -24,7 +24,7 @@ pub async fn healthcheck(
log::trace!("Sending PING..."); log::trace!("Sending PING...");
let response = redis::cmd("PING") let response = redis::cmd("PING")
.query_async::<redis::aio::Connection, String>(&mut rconn).await .query_async::<redis::aio::Connection, String>(&mut rconn).await
.unwrap_or_500_and_log()?; .expect_or_500_and_log("Failed to PING Redis")?;
log::trace!("Sent PING and received: {:?}", response); log::trace!("Sent PING and received: {:?}", response);

View file

@ -1,20 +1,32 @@
use std::fmt::Debug;
use async_trait::async_trait; use async_trait::async_trait;
use axum::http::StatusCode; use axum::http::StatusCode;
pub type Result<T> = std::result::Result<T, StatusCode>; pub type Result<T> = std::result::Result<T, StatusCode>;
pub(crate) trait RedisUnwrapOr500<T> { pub(crate) trait UnwrapOr500<T, E> {
fn unwrap_or_500_and_log(self) -> Result<T>; fn unwrap_or_500(self) -> Result<T>;
fn unwrap_or_500_and_log(self) -> Result<T> where E: Debug;
fn expect_or_500_and_log(self, text: &str) -> Result<T> where E: Debug;
} }
impl<T> RedisUnwrapOr500<T> for redis::RedisResult<T> { impl<T, E> UnwrapOr500<T, E> for std::result::Result<T, E> {
fn unwrap_or_500_and_log(self) -> Result<T> { fn unwrap_or_500(self) -> Result<T> {
self self.or(Err(StatusCode::INTERNAL_SERVER_ERROR))
.map_err(|e| { }
log::error!("{e:#?}");
e fn unwrap_or_500_and_log(self) -> Result<T> where E: Debug {
}) self.map_err(|e| {
.or(Err(StatusCode::INTERNAL_SERVER_ERROR)) log::error!("{e:?}");
e
}).unwrap_or_500()
}
fn expect_or_500_and_log(self, text: &str) -> Result<T> where E: Debug {
self.map_err(|e| {
log::error!("{text}: {e:?}");
e
}).unwrap_or_500()
} }
} }
@ -29,7 +41,7 @@ impl RedisConnectOr500 for redis::Client {
log::trace!("Connecting to Redis..."); log::trace!("Connecting to Redis...");
let rconn = self.get_async_connection().await let rconn = self.get_async_connection().await
.unwrap_or_500_and_log()?; .expect_or_500_and_log("Failed to connect to Redis")?;
log::trace!("Connection successful!"); log::trace!("Connection successful!");
Ok(rconn) Ok(rconn)