Refactor project into workspaces

This commit is contained in:
Tobias Reisinger 2023-11-22 20:06:20 +01:00
parent 131bdeec78
commit bacea1e3e9
31 changed files with 119 additions and 99 deletions

View file

@ -1,82 +0,0 @@
use crate::db::errors::DatabaseError;
use actix_web::http::StatusCode;
use actix_web::HttpResponse;
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum ApiError {
BadUid,
ProtectedSchedule,
DatabaseError(DatabaseError),
InternalError(String),
}
impl ApiError {
fn get_code(&self) -> StatusCode {
match self {
ApiError::BadUid => StatusCode::BAD_REQUEST,
ApiError::ProtectedSchedule => StatusCode::FORBIDDEN,
ApiError::DatabaseError(db_error) => db_error.get_code(),
ApiError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
impl Serialize for ApiError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("error", 2)?;
s.serialize_field("code", &self.get_code().as_u16())?;
s.serialize_field("description", &String::from(self))?;
s.end()
}
}
impl From<&ApiError> for String {
fn from(err: &ApiError) -> Self {
match err {
ApiError::BadUid => String::from("the uid is in a bad format"),
ApiError::ProtectedSchedule => String::from("the targeted schedule is protected"),
ApiError::DatabaseError(db_err) => String::from(db_err),
ApiError::InternalError(msg) => msg.clone(),
}
}
}
impl From<&ApiError> for HttpResponse {
fn from(err: &ApiError) -> Self {
HttpResponse::build(err.get_code()).json(err)
}
}
impl Display for ApiError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.get_code(), String::from(self))
}
}
impl actix_web::error::ResponseError for ApiError {
fn status_code(&self) -> StatusCode {
self.get_code()
}
fn error_response(&self) -> HttpResponse {
HttpResponse::from(self)
}
}
impl From<sqlx::Error> for ApiError {
fn from(err: sqlx::Error) -> Self {
ApiError::DatabaseError(DatabaseError::from(err))
}
}
impl From<DatabaseError> for ApiError {
fn from(err: DatabaseError) -> Self {
ApiError::DatabaseError(err)
}
}

View file

@ -1,38 +0,0 @@
use actix_web::{error, Error, HttpRequest, HttpResponse};
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
pub(crate) mod errors;
pub mod v1;
enum EmgauwaJsonPayLoadError {
Error(error::JsonPayloadError),
}
impl Serialize for EmgauwaJsonPayLoadError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut s = serializer.serialize_struct("error", 3)?;
s.serialize_field("type", "json-payload-error")?;
s.serialize_field("code", &400)?;
s.serialize_field(
"description",
&match self {
EmgauwaJsonPayLoadError::Error(err) => format!("{}", err),
},
)?;
s.end()
}
}
pub fn json_error_handler(err: error::JsonPayloadError, _: &HttpRequest) -> Error {
error::InternalError::from_response(
"",
HttpResponse::BadRequest()
.content_type("application/json")
.json(EmgauwaJsonPayLoadError::Error(err)),
)
.into()
}

View file

@ -1,2 +0,0 @@
pub mod schedules;
pub mod ws;

View file

@ -1,189 +0,0 @@
use std::borrow::Borrow;
use std::convert::TryFrom;
use actix_web::{delete, get, post, put, web, HttpResponse};
use serde::{Deserialize, Serialize};
use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite};
use crate::db::errors::DatabaseError;
use crate::db::schedules::*;
use crate::db::tag::Tag;
use crate::handlers::errors::ApiError;
use crate::return_models::ReturnSchedule;
use crate::types::EmgauwaUid;
use crate::utils::vec_has_error;
#[derive(Debug, Serialize, Deserialize)]
pub struct RequestSchedule {
name: String,
periods: Periods,
tags: Vec<String>,
}
#[get("/api/v1/schedules")]
pub async fn index(pool: web::Data<Pool<Sqlite>>) -> Result<HttpResponse, ApiError> {
let mut pool_conn = pool.acquire().await?;
let schedules = Schedule::get_all(&mut pool_conn).await?;
let mut return_schedules: Vec<ReturnSchedule> =
schedules.iter().map(ReturnSchedule::from).collect();
for schedule in return_schedules.iter_mut() {
schedule.load_tags(&mut pool_conn);
}
Ok(HttpResponse::Ok().json(return_schedules))
}
#[get("/api/v1/schedules/tag/{tag}")]
pub async fn tagged(
pool: web::Data<Pool<Sqlite>>,
path: web::Path<(String,)>,
) -> Result<HttpResponse, ApiError> {
let mut pool_conn = pool.acquire().await?;
let (tag,) = path.into_inner();
let tag_db = Tag::get(&mut pool_conn, &tag).await?;
let schedules = Schedule::get_by_tag(&mut pool_conn, &tag_db).await?;
let mut return_schedules: Vec<ReturnSchedule> =
schedules.iter().map(ReturnSchedule::from).collect();
for schedule in return_schedules.iter_mut() {
schedule.load_tags(&mut pool_conn);
}
Ok(HttpResponse::Ok().json(return_schedules))
}
#[get("/api/v1/schedules/{schedule_id}")]
pub async fn show(
pool: web::Data<Pool<Sqlite>>,
path: web::Path<(String,)>,
) -> Result<HttpResponse, ApiError> {
let mut pool_conn = pool.acquire().await?;
let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;
let schedule = Schedule::get_by_uid(&mut pool_conn, &emgauwa_uid).await?;
let mut return_schedule = ReturnSchedule::from(schedule);
return_schedule.load_tags(&mut pool_conn);
Ok(HttpResponse::Ok().json(return_schedule))
}
#[post("/api/v1/schedules")]
pub async fn add(
pool: web::Data<Pool<Sqlite>>,
data: web::Json<RequestSchedule>,
) -> Result<HttpResponse, ApiError> {
let mut pool_conn = pool.acquire().await?;
let new_schedule = Schedule::create(&mut pool_conn, &data.name, &data.periods).await?;
new_schedule
.set_tags(&mut pool_conn, data.tags.as_slice())
.await?;
let mut return_schedule = ReturnSchedule::from(new_schedule);
return_schedule.load_tags(&mut pool_conn);
Ok(HttpResponse::Created().json(return_schedule))
}
async fn add_list_single(
conn: &mut PoolConnection<Sqlite>,
request_schedule: &RequestSchedule,
) -> Result<Schedule, DatabaseError> {
let new_schedule =
Schedule::create(conn, &request_schedule.name, &request_schedule.periods).await?;
new_schedule
.set_tags(conn, request_schedule.tags.as_slice())
.await?;
Ok(new_schedule)
}
#[post("/api/v1/schedules/list")]
pub async fn add_list(
pool: web::Data<Pool<Sqlite>>,
data: web::Json<Vec<RequestSchedule>>,
) -> Result<HttpResponse, ApiError> {
let mut pool_conn = pool.acquire().await?;
let result: Vec<Result<Schedule, DatabaseError>> = data
.as_slice()
.iter()
.map(|request_schedule| {
futures::executor::block_on(add_list_single(&mut pool_conn, request_schedule))
})
.collect();
match vec_has_error(&result) {
true => Ok(HttpResponse::from(
result
.into_iter()
.find(|r| r.is_err())
.unwrap()
.unwrap_err(),
)),
false => {
let mut return_schedules: Vec<ReturnSchedule> = result
.iter()
.map(|s| ReturnSchedule::from(s.as_ref().unwrap()))
.collect();
for schedule in return_schedules.iter_mut() {
schedule.load_tags(&mut pool_conn);
}
Ok(HttpResponse::Created().json(return_schedules))
}
}
}
#[put("/api/v1/schedules/{schedule_id}")]
pub async fn update(
pool: web::Data<Pool<Sqlite>>,
path: web::Path<(String,)>,
data: web::Json<RequestSchedule>,
) -> Result<HttpResponse, ApiError> {
let mut pool_conn = pool.acquire().await?;
let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;
let schedule = Schedule::get_by_uid(&mut pool_conn, &emgauwa_uid).await?;
let schedule = schedule
.update(&mut pool_conn, data.name.as_str(), data.periods.borrow())
.await?;
schedule
.set_tags(&mut pool_conn, data.tags.as_slice())
.await?;
let mut return_schedule = ReturnSchedule::from(schedule);
return_schedule.load_tags(&mut pool_conn);
Ok(HttpResponse::Ok().json(return_schedule))
}
#[delete("/api/v1/schedules/{schedule_id}")]
pub async fn delete(
pool: web::Data<Pool<Sqlite>>,
path: web::Path<(String,)>,
) -> Result<HttpResponse, ApiError> {
let mut pool_conn = pool.acquire().await?;
let (schedule_uid,) = path.into_inner();
let emgauwa_uid = EmgauwaUid::try_from(schedule_uid.as_str()).or(Err(ApiError::BadUid))?;
match emgauwa_uid {
EmgauwaUid::Off => Err(ApiError::ProtectedSchedule),
EmgauwaUid::On => Err(ApiError::ProtectedSchedule),
EmgauwaUid::Any(_) => {
Schedule::delete_by_uid(&mut pool_conn, emgauwa_uid).await?;
Ok(HttpResponse::Ok().json("schedule got deleted"))
}
}
}

View file

@ -1,53 +0,0 @@
use crate::db::schedules::Schedule;
use crate::handlers::errors::ApiError;
use actix::{Actor, StreamHandler};
use actix_web::{get, web, HttpRequest, HttpResponse};
use actix_web_actors::ws;
use actix_web_actors::ws::ProtocolError;
use sqlx::{Pool, Sqlite};
use ws::Message;
struct ControllerWs {
pub pool: Pool<Sqlite>,
}
impl Actor for ControllerWs {
type Context = ws::WebsocketContext<Self>;
}
async fn get_schedules(pool: &mut Pool<Sqlite>) -> Result<Vec<Schedule>, ApiError> {
let mut pool_conn = pool.acquire().await?;
Ok(Schedule::get_all(&mut pool_conn).await?)
}
/// Handler for ws::Message message
impl StreamHandler<Result<Message, ProtocolError>> for ControllerWs {
fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
let schedules = futures::executor::block_on(get_schedules(&mut self.pool)).unwrap();
let schedules_json = serde_json::to_string(&schedules).unwrap();
match msg {
Ok(Message::Ping(msg)) => ctx.pong(&msg),
Ok(Message::Text(_text)) => ctx.text(schedules_json),
_ => {}
}
}
}
#[get("/api/v1/ws/controllers")]
pub async fn index(
pool: web::Data<Pool<Sqlite>>,
req: HttpRequest,
stream: web::Payload,
) -> Result<HttpResponse, ApiError> {
let resp = ws::start(
ControllerWs {
pool: pool.get_ref().clone(),
},
&req,
stream,
)
.map_err(|_| ApiError::InternalError(String::from("error starting websocket")));
println!("{:?}", resp);
resp
}

View file

@ -1 +0,0 @@
pub mod controllers;