Updates all libraries and some cleanup in the Rust part.

This commit is contained in:
2022-06-03 19:49:51 +02:00
parent 5ace39d820
commit 34737bfb6b
7 changed files with 212 additions and 354 deletions

View File

@@ -21,19 +21,25 @@ pub enum ApiResponseVariant {
Value(Value),
}
#[derive(Serialize, Deserialize, Debug)]
pub enum ApiData {
#[serde(rename = "user")]
User(UserWithToken),
#[serde(rename = "gamenights")]
Gamenights(Vec<GamenightOutput>),
#[serde(rename = "gamenight")]
Gamenight(GamenightOutput),
#[serde(rename = "games")]
Games(Vec<Game>),
}
#[derive(Serialize, Deserialize, Debug)]
struct ApiResponse {
result: Cow<'static, str>,
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<Cow<'static, str>>,
#[serde(skip_serializing_if = "Option::is_none")]
user: Option<UserWithToken>,
#[serde(skip_serializing_if = "Option::is_none")]
gamenights: Option<Vec<GamenightOutput>>,
#[serde(skip_serializing_if = "Option::is_none")]
gamenight: Option<GamenightOutput>,
#[serde(skip_serializing_if = "Option::is_none")]
games: Option<Vec<Game>>,
#[serde(flatten, skip_serializing_if = "Option::is_none")]
data: Option<ApiData>,
}
impl ApiResponse {
@@ -43,20 +49,14 @@ impl ApiResponse {
const SUCCES: Self = Self {
result: Self::SUCCES_RESULT,
message: None,
user: None,
gamenights: None,
gamenight: None,
games: None,
data: None,
};
fn error(message: String) -> Self {
Self {
result: Self::FAILURE_RESULT,
message: Some(Cow::Owned(message)),
user: None,
gamenights: None,
gamenight: None,
games: None,
data: None,
}
}
@@ -64,13 +64,10 @@ impl ApiResponse {
Self {
result: Self::SUCCES_RESULT,
message: None,
user: Some(UserWithToken {
data: Some(ApiData::User(UserWithToken {
user: user,
jwt: jwt,
}),
gamenights: None,
gamenight: None,
games: None,
})),
}
}
@@ -78,21 +75,15 @@ impl ApiResponse {
Self {
result: Self::SUCCES_RESULT,
message: None,
user: None,
gamenights: Some(gamenights),
gamenight: None,
games: None,
data: Some(ApiData::Gamenights(gamenights)),
}
}
fn gamenight_response(gamenight: GamenightOutput) -> Self {
Self {
result: Self::SUCCES_RESULT,
message: None,
user: None,
gamenights: None,
gamenight: Some(gamenight),
games: None,
data: Some(ApiData::Gamenight(gamenight)),
}
}
@@ -100,10 +91,7 @@ impl ApiResponse {
Self {
result: Self::SUCCES_RESULT,
message: None,
user: None,
gamenights: None,
gamenight: None,
games: Some(games),
data: Some(ApiData::Games(games)),
}
}
}
@@ -160,35 +148,44 @@ pub struct GamenightOutput {
#[derive(Debug, Serialize, Deserialize)]
pub struct GamenightUpdate {
action: String
action: String,
}
#[patch("/gamenights/<gamenight_id>", format = "application/json", data = "<patch_json>")]
pub async fn patch_gamenight(conn: DbConn, user: User, gamenight_id: String, patch_json: Json<GamenightUpdate>) -> ApiResponseVariant {
#[patch(
"/gamenights/<gamenight_id>",
format = "application/json",
data = "<patch_json>"
)]
pub async fn patch_gamenight(
conn: DbConn,
user: User,
gamenight_id: String,
patch_json: Json<GamenightUpdate>,
) -> ApiResponseVariant {
let uuid = Uuid::parse_str(&gamenight_id).unwrap();
let patch = patch_json.into_inner();
match patch.action.as_str() {
"RemoveParticipant" => {
let entry = GamenightParticipantsEntry {
gamenight_id: uuid,
user_id: user.id
user_id: user.id,
};
match remove_participant(&conn, entry).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string())))
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
"AddParticipant" => {
let entry = GamenightParticipantsEntry {
gamenight_id: uuid,
user_id: user.id
user_id: user.id,
};
match add_participant(&conn, entry).await {
Ok(_) => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string())))
Err(err) => ApiResponseVariant::Value(json!(ApiResponse::error(err.to_string()))),
}
}
_ => ApiResponseVariant::Value(json!(ApiResponse::SUCCES))
_ => ApiResponseVariant::Value(json!(ApiResponse::SUCCES)),
}
}
@@ -210,9 +207,9 @@ pub async fn gamenight(conn: DbConn, _user: User, gamenight_id: String) -> ApiRe
let gamenight_output = GamenightOutput {
gamenight: gamenight,
game_list: games,
participants: participants
participants: participants,
};
return ApiResponseVariant::Value(json!(ApiResponse::gamenight_response(gamenight_output)))
return ApiResponseVariant::Value(json!(ApiResponse::gamenight_response(gamenight_output)));
}
#[get("/gamenights")]

View File

@@ -43,9 +43,9 @@ async fn rocket() -> _ {
let rocket = rocket::custom(figment)
.attach(schema::DbConn::fairing())
.attach(Template::fairing())
.attach(site::CORS)
.attach(AdHoc::on_ignite("Run Migrations", schema::run_migrations))
.attach(AdHoc::config::<AppConfig>())
.attach(site::make_cors())
.mount("/", routes![site::index, site::files])
.mount(
"/api",

View File

@@ -204,12 +204,6 @@ pub async fn add_participant(
.await?)
}
impl From<GamenightParticipantsEntry> for (Uuid, Uuid) {
fn from(entry: GamenightParticipantsEntry) -> Self {
(entry.gamenight_id, entry.user_id)
}
}
pub async fn remove_participant(
conn: &DbConn,
participant: GamenightParticipantsEntry,

View File

@@ -1,32 +1,32 @@
use local_ip_address::local_ip;
use rocket::fs::NamedFile;
use rocket::http::Method;
use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors, CorsOptions};
use rocket::{
fairing::{Fairing, Info, Kind},
http::Header,
Request, Response,
};
use std::io;
use std::path::{Path, PathBuf};
pub fn make_cors() -> Cors {
let allowed_origins = AllowedOrigins::some_exact(&[
"http://localhost:3000",
"http://127.0.0.1:3000",
&format!("http://{}:8000", local_ip().unwrap())[..],
"http://localhost:8000",
"http://0.0.0.0:8000",
]);
pub struct CORS;
CorsOptions {
allowed_origins,
allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(), // 1.
allowed_headers: AllowedHeaders::some(&[
"Authorization",
"Accept",
"Access-Control-Allow-Origin",
]),
allow_credentials: true,
..Default::default()
#[rocket::async_trait]
impl Fairing for CORS {
fn info(&self) -> Info {
Info {
name: "Attaching CORS headers to responses",
kind: Kind::Response,
}
}
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
response.set_header(Header::new(
"Access-Control-Allow-Methods",
"POST, GET, PATCH, OPTIONS",
));
response.set_header(Header::new("Access-Control-Allow-Headers", "*"));
response.set_header(Header::new("Access-Control-Allow-Credentials", "true"));
}
.to_cors()
.expect("error while building CORS")
}
#[get("/<file..>", rank = 10)]