forked from Roflin/gamenight
70 lines
2.6 KiB
Rust
70 lines
2.6 KiB
Rust
use actix_web::{get, web, Responder, http::header::ContentType, HttpResponse, post};
|
|
use chrono::{DateTime, ParseError};
|
|
use uuid::Uuid;
|
|
|
|
use gamenight_database::{gamenight, DbPool, GetConnection};
|
|
|
|
use crate::{models::{add_gamenight_request_body::AddGamenightRequestBody, gamenight::Gamenight, get_gamenight_request_body::GetGamenightRequestBody}, request::authorization::AuthUser};
|
|
use crate::request::error::ApiError;
|
|
|
|
|
|
impl AddGamenightRequestBody {
|
|
pub fn into_with_user(&self, user: AuthUser) -> Result<gamenight::Gamenight, ParseError> {
|
|
Ok(gamenight::Gamenight {
|
|
datetime: DateTime::parse_from_rfc3339(&self.clone().datetime.unwrap())?.with_timezone(&chrono::Utc),
|
|
id: Uuid::new_v4(),
|
|
name: self.clone().name.unwrap().clone(),
|
|
owner_id: user.id
|
|
})
|
|
}
|
|
}
|
|
|
|
impl From<GetGamenightRequestBody> for Uuid {
|
|
fn from(value: GetGamenightRequestBody) -> Self {
|
|
Uuid::parse_str(value.id.unwrap().as_str()).unwrap()
|
|
}
|
|
}
|
|
|
|
#[get("/gamenights")]
|
|
pub async fn gamenights(pool: web::Data<DbPool>, _user: AuthUser) -> Result<impl Responder, ApiError> {
|
|
let mut conn = pool.get_conn();
|
|
let gamenights: Vec<gamenight::Gamenight> = gamenight_database::gamenights(&mut conn)?;
|
|
let model: Vec<Gamenight> = gamenights.iter().map(|x| {
|
|
Gamenight {
|
|
id: x.id.to_string(),
|
|
name: x.name.clone(),
|
|
datetime: x.datetime.to_rfc3339(),
|
|
owner_id: x.owner_id.to_string()
|
|
}}
|
|
).collect();
|
|
|
|
Ok(HttpResponse::Ok()
|
|
.content_type(ContentType::json())
|
|
.body(serde_json::to_string(&model)?)
|
|
)
|
|
}
|
|
|
|
#[post("/gamenight")]
|
|
pub async fn gamenight_post(pool: web::Data<DbPool>, user: AuthUser, gamenight_data: web::Json<AddGamenightRequestBody>) -> Result<impl Responder, ApiError> {
|
|
let mut conn = pool.get_conn();
|
|
|
|
gamenight::add_gamenight(&mut conn, gamenight_data.into_with_user(user)?)?;
|
|
|
|
Ok(HttpResponse::Ok())
|
|
}
|
|
|
|
#[get("/gamenight")]
|
|
pub async fn gamenight_get(pool: web::Data<DbPool>, _user: AuthUser, gamenight_data: web::Json<GetGamenightRequestBody>) -> Result<impl Responder, ApiError> {
|
|
let mut conn = pool.get_conn();
|
|
let gamenight = gamenight::get_gamenight(&mut conn, gamenight_data.into_inner().into())?;
|
|
let model = Gamenight{
|
|
id: gamenight.id.to_string(),
|
|
datetime: gamenight.datetime.to_rfc3339(),
|
|
name: gamenight.name,
|
|
owner_id: gamenight.owner_id.to_string(),
|
|
};
|
|
|
|
Ok(HttpResponse::Ok()
|
|
.content_type(ContentType::json())
|
|
.body(serde_json::to_string(&model)?))
|
|
} |