use crate::namespace::{
self, Command, OperationStatus, Response, VarIdValue, command, response, value,
};
use crate::types::errors::ClientError;
pub(crate) fn ensure_ok(resp: &Response) -> Result<(), ClientError> {
match OperationStatus::try_from(resp.status).unwrap_or(OperationStatus::Invalid) {
OperationStatus::Ok => Ok(()),
OperationStatus::Err | OperationStatus::Invalid => Err(ClientError::OperationFailed(
resp.error_msg
.clone()
.unwrap_or_else(|| "unknown error".into()),
)),
}
}
pub(crate) fn extract_cmd_id_from_command(cmd: &Command) -> Option<&str> {
use command::CommandType::*;
match cmd.command_type.as_ref()? {
Add(c) => Some(&c.cmd_id),
List(c) => Some(&c.cmd_id),
Set(c) => Some(&c.cmd_id),
Get(c) => Some(&c.cmd_id),
Del(c) => Some(&c.cmd_id),
AddBulk(c) => Some(&c.cmd_id),
Sub(c) => Some(&c.cmd_id),
Unsub(c) => Some(&c.cmd_id),
EditMeta(c) => Some(&c.cmd_id),
}
}
pub(crate) fn extract_cmd_id_from_response(resp: &Response) -> Option<&str> {
use response::ResponseType::*;
match resp.response_type.as_ref()? {
Add(r) => Some(&r.cmd_id),
List(r) => Some(&r.cmd_id),
Set(r) => Some(&r.cmd_id),
Get(r) => Some(&r.cmd_id),
Del(r) => Some(&r.cmd_id),
Inv(r) => Some(&r.cmd_id),
AddBulk(r) => Some(&r.cmd_id),
Sub(r) => Some(&r.cmd_id),
Unsub(r) => Some(&r.cmd_id),
EditMeta(r) => Some(&r.cmd_id),
}
}
pub(crate) fn build_pairs<T, F>(
var_ids: Vec<String>,
values: Vec<T>,
to_typed: F,
) -> Result<Vec<VarIdValue>, ClientError>
where
F: Fn(T) -> value::Typed,
{
if var_ids.len() != values.len() {
return Err(ClientError::InvalidInput(
"var_ids and values must have same length",
));
}
let iter = var_ids.into_iter().zip(values);
let pairs = iter
.map(|(id, v)| VarIdValue {
var_id: id,
value: Some(namespace::Value {
typed: Some(to_typed(v)),
}),
})
.collect();
Ok(pairs)
}