Files
aviation/api/src/account/user_favorites.rs
2025-09-19 19:33:53 -04:00

62 lines
1.3 KiB
Rust

use crate::error::ApiResult;
use serde::Deserialize;
use sqlx::{Pool, Postgres};
const TABLE_NAME: &str = "user_airport_favorites";
#[derive(Debug, Deserialize, sqlx::FromRow)]
pub struct UserFavorite {
pub username: String,
pub icao: String,
}
impl UserFavorite {
pub async fn select_all(pool: &Pool<Postgres>, username: &str) -> ApiResult<Vec<String>> {
let user_favorites: Vec<UserFavorite> = sqlx::query_as::<_, UserFavorite>(&format!(
r#"
SELECT * FROM {} WHERE username = $1
"#,
TABLE_NAME
))
.bind(username)
.fetch_all(pool)
.await?;
let favorites = user_favorites.iter().map(|uf| uf.icao.clone()).collect();
Ok(favorites)
}
pub async fn insert(pool: &Pool<Postgres>, username: &str, icao: &str) -> ApiResult<()> {
sqlx::query(&format!(
r#"
INSERT INTO {} (
username, icao
) VALUES ($1, $2)
"#,
TABLE_NAME
))
.bind(username)
.bind(icao)
.execute(pool)
.await?;
Ok(())
}
pub async fn delete(pool: &Pool<Postgres>, username: &str, icao: &str) -> ApiResult<()> {
sqlx::query(&format!(
r#"
DELETE FROM {} WHERE username = $1 AND icao = $2
"#,
TABLE_NAME
))
.bind(username)
.bind(icao)
.execute(pool)
.await?;
Ok(())
}
}