embedded_redis/commands/custom.rs
1//! Abstraction for arbitrary commands.
2//!
3//! [CustomCommand] in combination with [CommandBuilder] can be used for executing arbitrary commands,
4//! which high level logic is not abstracted yet by this crate.
5//!
6//! Response is not evaluated, so pure [Resp2Frame](redis_protocol::resp2::types::BytesFrame)
7//! or [Resp3Frame](redis_protocol::resp3::types::BytesFrame) is returned.
8//! The only exception is that error responses are intercepted and converted to [CommandErrors::ErrorResponse](crate::network::CommandErrors::ErrorResponse)
9//!
10//! *Please consider contributing command abstractions not supported yet.*
11//!
12//! # Basic usage
13//! The following Example demonstrates execution of [ECHO](<https://redis.io/commands/echo/>) command
14//! ```
15//!# use core::str::FromStr;
16//!# use core::net::SocketAddr;
17//!# use std_embedded_nal::Stack;
18//!# use std_embedded_time::StandardClock;
19//!# use embedded_redis::commands::builder::CommandBuilder;
20//!# use embedded_redis::network::ConnectionHandler;
21//!# use redis_protocol::resp2::types::Resp2Frame;
22//!#
23//! let mut stack = Stack::default();
24//! let clock = StandardClock::default();
25//!
26//! let mut connection_handler = ConnectionHandler::resp2(SocketAddr::from_str("127.0.0.1:6379").unwrap());
27//! let client = connection_handler.connect(&mut stack, Some(&clock)).unwrap();
28//!
29//! let command = CommandBuilder::new("ECHO").arg_static("Hello World!").to_command();
30//! let response = client.send(command).unwrap().wait().unwrap();
31//! assert_eq!("Hello World!", response.to_string().unwrap());
32//! ```
33use crate::commands::builder::CommandBuilder;
34use crate::commands::{Command, ResponseTypeError};
35
36/// Abstraction for arbitrary commands.
37pub struct CustomCommand {
38 builder: CommandBuilder,
39}
40
41impl CustomCommand {
42 pub fn new(builder: CommandBuilder) -> Self {
43 CustomCommand { builder }
44 }
45}
46
47impl<F> Command<F> for CustomCommand
48where
49 F: From<CommandBuilder>,
50{
51 type Response = F;
52
53 fn encode(&self) -> F {
54 self.builder.clone().into()
55 }
56
57 fn eval_response(&self, frame: F) -> Result<Self::Response, ResponseTypeError> {
58 Ok(frame)
59 }
60}