Missing cast to array type
Closed this issue · 3 comments
Hi I'm not sure if is missing or just not clear, I need to ger from redis, the result of "LARANGE key 0 -1" redis command. But I can not make any cast as_array() or just response.as<std::vevtor std::string >();
How should I parse the result of a LRANGE command ?
Thanks !
Hi.
Sorry,I've just seen your message.
Taking an array from the response is not so easy at first glance. The array is a complex structure and --according to the gist of the library-- in order to get items of the complex structure there is a way through the visiting types of the response. Why so? The common idea was to provide the most common approach to work with a set of the different responses.
Considering, combining, and playing with the examples you could do something like I've made below
// STD
#include <cstdlib>
#include <iostream>
#include <redis-cpp/stream.h>
#include <redis-cpp/execute.h>
namespace respds = rediscpp::resp::deserialization;
void print_value(respds::array::item_type const &value, std::ostream &stream)
{
std::visit(rediscpp::resp::detail::overloaded{
[&stream] (respds::simple_string const &val)
{ stream << "Simple string: " << val.get() << std::endl; },
[&stream] (respds::error_message const &val)
{ stream << "Error message: " << val.get() << std::endl; },
[&stream] (respds::bulk_string const &val)
{ stream << "Bulk string: " << val.get() << std::endl; },
[&stream] (respds::integer const &val)
{ stream << "Integer: " << val.get() << std::endl; },
[&stream] (respds::array const &val)
{
stream << "----- Array -----" << std::endl;
for (auto const &i : val.get())
print_value(i, stream);
stream << "-----------------" << std::endl;
},
[&stream] (auto const &)
{ stream << "Unexpected value type." << std::endl; }
}, value);
}
int main()
{
try
{
auto stream = rediscpp::make_stream("localhost", "6379");
auto const key = "mylist";
for (int i = 0 ; i < 10 ; ++i)
{
auto response = rediscpp::execute(*stream, "RPUSH",
key, "Value " + std::to_string(i));
std::cout << "Set key '" << key << "': " << response.as<std::int32_t>() << std::endl;
}
auto response = rediscpp::execute(*stream, "LRANGE", key, "-100", "100");
print_value(response.get(), std::cout);
}
catch (std::exception const &e)
{
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Regards
I've just added a couple of functions in order to provide convenient casting for the plain arrays (as_string_array and as_integer_array). Hopefully, that'll make easier array type casting.
Thank you for your response. I have implemented a function similar print_value and worked.
For me is OK
Best regards and very good job