From 4aa90cdefbb97626ef2098b24f18afb1268ed957 Mon Sep 17 00:00:00 2001 From: Ethan Girouard Date: Sun, 19 May 2024 16:02:39 -0400 Subject: [PATCH] Add API functions for getting/adding history --- src/api/history.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/api/mod.rs | 1 + 2 files changed, 45 insertions(+) create mode 100644 src/api/history.rs diff --git a/src/api/history.rs b/src/api/history.rs new file mode 100644 index 0000000..5f6cabb --- /dev/null +++ b/src/api/history.rs @@ -0,0 +1,44 @@ +use std::time::SystemTime; +use leptos::*; +use crate::models::HistoryEntry; +use crate::models::Song; + +use cfg_if::cfg_if; + +cfg_if! { + if #[cfg(feature = "ssr")] { + use leptos::server_fn::error::NoCustomError; + use crate::database::get_db_conn; + use crate::auth::get_user; + } +} + +/// Get the history of the current user. +#[server(endpoint = "history/get")] +pub async fn get_history(limit: Option) -> Result, ServerFnError> { + let user = get_user().await?; + let db_con = &mut get_db_conn(); + let history = user.get_history(limit, db_con) + .map_err(|e| ServerFnError::::ServerError(format!("Error getting history: {}", e)))?; + Ok(history) +} + +/// Get the listen dates and songs of the current user. +#[server(endpoint = "history/get_songs")] +pub async fn get_history_songs(limit: Option) -> Result, ServerFnError> { + let user = get_user().await?; + let db_con = &mut get_db_conn(); + let songs = user.get_history_songs(limit, db_con) + .map_err(|e| ServerFnError::::ServerError(format!("Error getting history songs: {}", e)))?; + Ok(songs) +} + +/// Add a song to the history of the current user. +#[server(endpoint = "history/add")] +pub async fn add_history(song_id: i32) -> Result<(), ServerFnError> { + let user = get_user().await?; + let db_con = &mut get_db_conn(); + user.add_history(song_id, db_con) + .map_err(|e| ServerFnError::::ServerError(format!("Error adding history: {}", e)))?; + Ok(()) +} diff --git a/src/api/mod.rs b/src/api/mod.rs index e69de29..2b44c34 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -0,0 +1 @@ +pub mod history;