view src/http.rs @ 36:ebdb9c50adb1

Better responses, more database encapsulation
author Lewin Bormann <lbo@spheniscida.de>
date Thu, 03 Dec 2020 09:25:29 +0100
parents
children 08b4f7127980
line wrap: on
line source


use rocket::response::Responder;

#[derive(Responder)]
pub enum GeoHubResponse {
    #[response(status=200, content_type="json")]
    Ok(String),
    #[response(status=400)]
    BadRequest(String),
    #[response(status=500)]
    ServerError(String),
}

pub fn return_json<T: serde::Serialize>(obj: &T) -> GeoHubResponse {
    let json = serde_json::to_string(&obj);
    if let Ok(json) = json {
        return GeoHubResponse::Ok(json);
    } else {
        return GeoHubResponse::ServerError(json.unwrap_err().to_string());
    }
}

pub fn bad_request(msg: String) -> GeoHubResponse {
    GeoHubResponse::BadRequest(msg)
}

pub fn server_error(msg: String) -> GeoHubResponse {
    GeoHubResponse::ServerError(msg)
}