redis-macros 1.0.1

Simple macros and wrappers to redis-rs to automatically serialize and deserialize structs with serde.
Documentation
use redis::{ParsingError, Value};
use serde::de::DeserializeOwned;

/// Json struct is a wrapper to handle the return types from the RedisJSON commands.
///
/// RedisJSON usually returns values in square brackets, which you usually had to handle manually:
///
/// ```rust,no_run
/// # use redis::{Client, JsonCommands, RedisResult};
/// # use redis_macros::{FromRedisValue, ToRedisArgs, Json};
/// # use serde::{Deserialize, Serialize};
/// # #[derive(Serialize, Deserialize)]
/// # struct User { id: u32 }
/// #
/// # fn main () -> redis::RedisResult<()> {
/// # let client = redis::Client::open("redis://localhost:6379/")?;
/// # let mut con = client.get_connection()?;
/// # let _: () = con.json_set("user", "$", &r#"{ "id": 1 }"#)?;
/// // You have to manually deserialize this and pull from the Vec
/// let user_id: String = con.json_get("user", "$.id")?;  // => "[1]"
/// # Ok(())
/// # }
/// ```
///
/// Instead, `Json` implements the `FromRedisValue` trait, removes the square brackets and deserializes from JSON.
/// For this your type don't even have to implement `FromRedisValue`, it only requires to be serde `Deserialize`-able.
///
/// ```rust,no_run
/// # use redis::{Client, JsonCommands, RedisResult};
/// # use redis_macros::Json;
/// # use serde::{Deserialize, Serialize};
/// #[derive(Serialize, Deserialize)]
/// struct User { id: u32 }
///
/// # fn main () -> redis::RedisResult<()> {
/// # let client = redis::Client::open("redis://localhost:6379/")?;
/// # let mut con = client.get_connection()?;
/// # let _: () = con.json_set("user", "$", &r#"{ "id": 1 }"#)?;
/// let Json(user_id): Json<u32> = con.json_get("user", "$.id")?;  // => 1
/// let Json(user): Json<User> = con.json_get("user", "$")?;  // => User { id: 1 }
/// # Ok(())
/// # }
/// ```
///
/// This command is designed to use RedisJSON commands. You could probably use this type
/// to parse normal command outputs, but it removes the first and last character
/// so it is not recommended.
///
#[derive(Debug)]
pub struct Json<T>(
    /// The inner type to deserialize
    pub T,
);

impl<T> ::redis::FromRedisValue for Json<T>
where
    T: DeserializeOwned,
{
    fn from_redis_value(v: Value) -> Result<Json<T>, ParsingError> {
        let Value::BulkString(bytes) = &v else {
            return Err(format!(
                "Response type in JSON was not deserializable. (response was {v:?})"
            )
            .into());
        };

        let s = ::std::str::from_utf8(bytes).map_err(|e| {
            format!("Response type in JSON is invalid UTF-8: {e}. (response was {v:?})")
        })?;
        let mut ch = s.chars();
        if !(ch.next() == Some('[') && ch.next_back() == Some(']')) {
            return Err(format!(
                "Response type in JSON was not deserializable. (response was {v:?})"
            )
            .into());
        }
        let deser = serde_json::from_str(ch.as_str()).map_err(|e| {
            format!("Response type in JSON could not be deserialized: {e} (response was {v:?})")
        })?;
        Ok(Json(deser))
    }
}