rustis/client/
prepared_command.rs

1use crate::{
2    Future,
3    client::Client,
4    resp::{Command, RespBuf, Response},
5};
6use std::marker::PhantomData;
7
8type CustomConverter<'a, R> = dyn Fn(RespBuf, Command, &'a Client) -> Future<'a, R> + Send + Sync;
9
10/// Wrapper around a command about to be send with a marker for the response type
11/// and a few options to decide how the response send back by Redis should be processed.
12pub struct PreparedCommand<'a, E, R = ()>
13where
14    R: Response,
15{
16    /// Marker of the type in which the command response will be transformed
17    phantom: PhantomData<R>,
18    /// Client, Transaction or Pipeline that will actually
19    /// send the command to the Redis server.
20    pub executor: E,
21    /// Command to send
22    pub command: Command,
23    /// Custom converter to transform a RESP Buffer in to `R` type
24    pub custom_converter: Option<Box<CustomConverter<'a, R>>>,
25    /// Flag to retry sending the command on network error.
26    pub retry_on_error: Option<bool>,
27}
28
29impl<'a, E, R> PreparedCommand<'a, E, R>
30where
31    R: Response,
32{
33    /// Create a new prepared command.
34    #[must_use]
35    pub fn new(executor: E, command: Command) -> Self {
36        PreparedCommand {
37            phantom: PhantomData,
38            executor,
39            command,
40            custom_converter: None,
41            retry_on_error: None,
42        }
43    }
44
45    /// Set the functor [`PreparedCommand::custom_converter`]
46    pub fn custom_converter(mut self, custom_converter: Box<CustomConverter<'a, R>>) -> Self {
47        self.custom_converter = Some(custom_converter);
48        self
49    }
50
51    /// Set a flag to override default `retry_on_error` behavior.
52    ///
53    /// See [Config::retry_on_error](crate::client::Config::retry_on_error)
54    pub fn retry_on_error(mut self, retry_on_error: bool) -> Self {
55        self.retry_on_error = Some(retry_on_error);
56        self
57    }
58
59    /// Get a reference to the command to send
60    pub fn command(&self) -> &Command {
61        &self.command
62    }
63}
64
65/// Shortcut function to creating a [`PreparedCommand`](PreparedCommand).
66pub(crate) fn prepare_command<'a, E, R: Response>(
67    executor: E,
68    command: impl Into<Command>,
69) -> PreparedCommand<'a, E, R> {
70    PreparedCommand::new(executor, command.into())
71}