forked from Roflin/gamenight
57 lines
1.8 KiB
Rust
57 lines
1.8 KiB
Rust
use actix_web::{get, post, web, HttpResponse, Responder};
|
|
use actix_web::http::header::ContentType;
|
|
use chrono::{DateTime, ParseError};
|
|
use gamenight_database::{gamenight, DbPool, GetConnection};
|
|
use uuid::Uuid;
|
|
use crate::models::add_gamenight_request_body::AddGamenightRequestBody;
|
|
use crate::models::gamenight::Gamenight;
|
|
use crate::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.datetime)?.with_timezone(&chrono::Utc),
|
|
id: Uuid::new_v4(),
|
|
name: self.name.clone(),
|
|
owner_id: user.0.id,
|
|
location_id: None,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[get("/gamenights")]
|
|
pub async fn get_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(),
|
|
location_id: x.location_id.map(|x| x.to_string()),
|
|
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("/gamenights")]
|
|
pub async fn post_gamenights(
|
|
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())
|
|
} |