Refactor project into workspaces
This commit is contained in:
parent
131bdeec78
commit
bacea1e3e9
31 changed files with 119 additions and 99 deletions
emgauwa-lib/src/handlers/v1
2
emgauwa-lib/src/handlers/v1/mod.rs
Normal file
2
emgauwa-lib/src/handlers/v1/mod.rs
Normal file
|
@ -0,0 +1,2 @@
|
|||
pub mod schedules;
|
||||
pub mod ws;
|
186
emgauwa-lib/src/handlers/v1/schedules.rs
Normal file
186
emgauwa-lib/src/handlers/v1/schedules.rs
Normal file
|
@ -0,0 +1,186 @@
|
|||
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::db::types::EmgauwaUid;
|
||||
use crate::handlers::errors::ApiError;
|
||||
use crate::return_models::ReturnSchedule;
|
||||
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)
|
||||
.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"))
|
||||
}
|
||||
}
|
||||
}
|
53
emgauwa-lib/src/handlers/v1/ws/controllers.rs
Normal file
53
emgauwa-lib/src/handlers/v1/ws/controllers.rs
Normal file
|
@ -0,0 +1,53 @@
|
|||
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
|
||||
}
|
1
emgauwa-lib/src/handlers/v1/ws/mod.rs
Normal file
1
emgauwa-lib/src/handlers/v1/ws/mod.rs
Normal file
|
@ -0,0 +1 @@
|
|||
pub mod controllers;
|
Loading…
Add table
Add a link
Reference in a new issue