1
0
mirror of https://gitlab.com/comunic/comunicapiv3 synced 2025-01-07 11:22:36 +00:00
comunicapiv3/src/data/http_request_handler.rs

56 lines
1.5 KiB
Rust
Raw Normal View History

2020-05-21 13:28:07 +00:00
use actix_web::{web, HttpRequest, HttpResponse};
use crate::controllers::routes::RequestResult;
use crate::data::http_error::HttpError;
use std::convert::TryFrom;
use std::error::Error;
use serde::Serialize;
/// Http request handler
///
/// @author Pierre Hubert
#[derive(Serialize)]
struct SuccessMessage {
success: String
}
pub struct HttpRequestHandler {
request: web::HttpRequest,
response: Option<web::HttpResponse>
}
impl HttpRequestHandler {
/// Construct a new request handler
pub fn new(req: HttpRequest) -> HttpRequestHandler {
HttpRequestHandler {
request: req,
response: None
}
}
/// Check if a response has been set for this request
pub fn has_response(&self) -> bool {
self.response.is_some()
}
/// Take the response from this struct
pub fn response(self) -> HttpResponse {
self.response.unwrap()
}
/// Success message
pub fn success(&mut self, message: &str) -> RequestResult {
self.response = Some(HttpResponse::Ok().json(SuccessMessage {
success: message.to_string()
}));
Ok(())
}
/// Internal error message
pub fn internal_error(&mut self, error: Box<dyn Error>) -> RequestResult {
self.response = Some(HttpResponse::InternalServerError().json(
HttpError::internal_error("Internal server error.")));
Err(Box::try_from(actix_web::error::ErrorInternalServerError(error)).unwrap())
}
}