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 } 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) -> RequestResult { self.response = Some(HttpResponse::InternalServerError().json( HttpError::internal_error("Internal server error."))); Err(Box::try_from(actix_web::error::ErrorInternalServerError(error)).unwrap()) } }