zero4rs 2.0.0

zero4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use crate::prelude2::*;

use std::collections::HashMap;

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct SimpileValue {
    pub id: u32,
    pub message: String,
}

pub async fn redis_set(
    query: web::Query<HashMap<String, String>>,
    body: web::Bytes,
    request: HttpRequest,
    app_state: web::Data<AppState>,
) -> impl Responder {
    let key = query
        .get("key")
        .cloned()
        .unwrap_or_else(|| String::from(""));

    let val = match crate::commons::bytes_to_string(body.to_vec()) {
        Ok(val) => val,
        Err(e) => return request.json(200, R::failed(500, e.to_string())),
    };

    app_state.redis().set(&key, &val, 60 * 5)?;

    match app_state.redis().get::<String>(&key) {
        Ok(val) => request.json(200, R::success(val, key)),
        Err(e) => request.json(200, R::failed(500, e.to_string())),
    }
}

pub async fn redis_set_value(
    query: web::Query<HashMap<String, String>>,
    message: web::Json<SimpileValue>,
    request: HttpRequest,
    app_state: web::Data<AppState>,
) -> impl Responder {
    let key = query
        .get("key")
        .cloned()
        .unwrap_or_else(|| String::from(""));

    app_state.redis().set(&key, &message, 60 * 5)?;

    match app_state.redis().get::<SimpileValue>(&key) {
        Ok(val) => request.json(200, R::success(val, key)),
        Err(e) => request.json(200, R::failed(500, e.to_string())),
    }
}

pub async fn redis_pub(
    query: web::Query<HashMap<String, String>>,
    body: web::Bytes,
    request: HttpRequest,
    app_state: web::Data<AppState>,
) -> impl Responder {
    let topic = query.get("topic").ok_or_else(|| {
        Errors::InvalidRequestError("Missing query string parameter: topic".to_string())
    })?;

    let message = match crate::commons::bytes_to_string(body.to_vec()) {
        Ok(val) => val,
        Err(e) => return request.json(200, R::failed(500, e.to_string())),
    };

    match app_state.redis().publish(topic, &message) {
        Ok(()) => request.json(200, R::success(message, String::from("message published"))),
        Err(e) => request.json(200, R::failed(500, e.to_string())),
    }
}