From 4846d74a957933291c398ac4f7c364a48b63b065 Mon Sep 17 00:00:00 2001 From: Jonni Liljamo Date: Mon, 13 Mar 2023 13:03:53 +0200 Subject: [PATCH] feat(shared): extract_cookie macro --- shared/src/api/macros.rs | 21 +++++++++++++++++++++ shared/src/api/mod.rs | 2 ++ shared/src/api/user/mod.rs | 20 +++----------------- 3 files changed, 26 insertions(+), 17 deletions(-) create mode 100644 shared/src/api/macros.rs diff --git a/shared/src/api/macros.rs b/shared/src/api/macros.rs new file mode 100644 index 0000000..3735946 --- /dev/null +++ b/shared/src/api/macros.rs @@ -0,0 +1,21 @@ +/* + * This file is part of laurelin/shared + * Copyright (C) 2023 Jonni Liljamo + * + * Licensed under GPL-3.0-only. + * See LICENSE for licensing information. + */ + +macro_rules! extract_cookie { + ($resp:expr) => {{ + let mut cookie = String::from(""); + for c in $resp.cookies() { + if c.name() == "id" { + cookie = c.value().to_string(); + } + } + cookie + }}; +} + +pub(super) use extract_cookie; diff --git a/shared/src/api/mod.rs b/shared/src/api/mod.rs index 7e9bd16..0f80c18 100644 --- a/shared/src/api/mod.rs +++ b/shared/src/api/mod.rs @@ -13,6 +13,8 @@ use serde::{Deserialize, Serialize}; pub mod types; pub mod user; +mod macros; + #[derive(Debug, Deserialize, Serialize)] pub struct APIError { pub id: u16, diff --git a/shared/src/api/user/mod.rs b/shared/src/api/user/mod.rs index 1fc30ee..958d563 100644 --- a/shared/src/api/user/mod.rs +++ b/shared/src/api/user/mod.rs @@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize}; use crate::error::api::APIError; -use super::types::User; +use super::{macros::extract_cookie, types::User}; #[derive(Serialize)] pub struct PostLogin { @@ -44,16 +44,9 @@ pub fn login(api_address: &str, email: &str, password: &str) -> ResponseLoginWra .send() .unwrap(); - let mut cookie = String::from(""); - for c in resp.cookies() { - if c.name() == "id" { - cookie = c.value().to_string(); - } - } - ResponseLoginWrapper { + cookie: extract_cookie!(resp), response: resp.json().unwrap(), - cookie, } } @@ -95,15 +88,8 @@ pub fn register( .send() .unwrap(); - let mut cookie = String::from(""); - for c in resp.cookies() { - if c.name() == "id" { - cookie = c.value().to_string(); - } - } - ResponseRegisterWrapper { + cookie: extract_cookie!(resp), response: resp.json().unwrap(), - cookie, } } -- 2.44.1