|
| 1 | +use std::convert::{TryFrom, TryInto}; |
| 2 | + |
| 3 | +use ntex::util::ByteString; |
| 4 | + |
1 | 5 | use super::{utils, Command, CommandError}; |
2 | 6 | use crate::codec::{BulkString, Request, Response}; |
3 | | -use std::convert::TryFrom; |
4 | 7 |
|
5 | 8 | /// DEL redis command |
6 | 9 | /// |
@@ -183,3 +186,57 @@ impl Command for TtlCommand { |
183 | 186 | }) |
184 | 187 | } |
185 | 188 | } |
| 189 | + |
| 190 | +/// KEYS redis command |
| 191 | +/// |
| 192 | +/// Returns all keys matching pattern. |
| 193 | +/// |
| 194 | +/// ```rust |
| 195 | +/// use ntex_redis::{cmd, RedisConnector}; |
| 196 | +/// # use rand::{thread_rng, Rng, distributions::Alphanumeric}; |
| 197 | +/// # fn gen_random_key() -> String { |
| 198 | +/// # thread_rng().sample_iter(&Alphanumeric).take(12).map(char::from).collect::<String>() |
| 199 | +/// # } |
| 200 | +/// |
| 201 | +/// #[ntex::main] |
| 202 | +/// async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 203 | +/// let redis = RedisConnector::new("127.0.0.1:6379").connect().await?; |
| 204 | +/// |
| 205 | +/// // set keys |
| 206 | +/// redis.exec(cmd::Set("firstname", "Jack")).await?; |
| 207 | +/// redis.exec(cmd::Set("lastname", "Stuntman")).await?; |
| 208 | +/// |
| 209 | +/// // get keys |
| 210 | +/// let mut keys = redis.exec(cmd::Keys("*name*")).await?; |
| 211 | +/// # keys.sort(); |
| 212 | +/// |
| 213 | +/// assert_eq!(&keys[..], &["firstname", "lastname"][..]); |
| 214 | +/// Ok(()) |
| 215 | +/// } |
| 216 | +/// ``` |
| 217 | +pub fn Keys<T>(key: T) -> KeysPatternCommand |
| 218 | +where |
| 219 | + BulkString: From<T>, |
| 220 | +{ |
| 221 | + KeysPatternCommand(Request::Array(vec![ |
| 222 | + Request::from_static("KEYS"), |
| 223 | + Request::BulkString(key.into()), |
| 224 | + ])) |
| 225 | +} |
| 226 | + |
| 227 | +pub struct KeysPatternCommand(Request); |
| 228 | + |
| 229 | +impl Command for KeysPatternCommand { |
| 230 | + type Output = Vec<ByteString>; |
| 231 | + |
| 232 | + fn to_request(self) -> Request { |
| 233 | + self.0 |
| 234 | + } |
| 235 | + |
| 236 | + fn to_output(val: Response) -> Result<Self::Output, CommandError> { |
| 237 | + match val.try_into() { |
| 238 | + Ok(val) => Ok(val), |
| 239 | + Err((_, val)) => Err(CommandError::Output("Cannot parse response", val)), |
| 240 | + } |
| 241 | + } |
| 242 | +} |
0 commit comments