add cache

This commit is contained in:
JMARyA 2024-08-08 13:06:02 +02:00
parent 96cd6ed0ef
commit d7652b8800
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
4 changed files with 161 additions and 7 deletions

View file

@ -9,9 +9,11 @@ use rocket::fs::NamedFile;
use rocket::*;
use serde_json::json;
use crate::cache::RouteCache;
use crate::library::album::Album;
use crate::library::Libary;
use crate::route::to_api;
use crate::use_api_cache;
#[get("/artist/<artist_id>/albums")]
pub async fn albums_route(artist_id: &str, lib: &State<Libary>) -> FallibleApiResponse {
@ -37,13 +39,31 @@ fn sort_by_tracknumber(a: &serde_json::Value, b: &serde_json::Value) -> Ordering
}
#[get("/album/<album_id>/cover")]
pub async fn album_cover_route(album_id: &str, lib: &State<Libary>) -> Option<NamedFile> {
let album = lib.get_album_by_id(album_id).await?;
NamedFile::open(album.get_cover().await?).await.ok()
pub async fn album_cover_route(
album_id: &str,
lib: &State<Libary>,
cache: &State<RouteCache>,
) -> Option<NamedFile> {
NamedFile::open(
cache
.get_option("album_cover_route", album_id, || async {
let album = lib.get_album_by_id(album_id).await?;
album.get_cover().await
})
.await?,
)
.await
.ok()
}
#[get("/album/<album_id>")]
pub async fn album_route(album_id: &str, lib: &State<Libary>) -> FallibleApiResponse {
pub async fn album_route(
album_id: &str,
lib: &State<Libary>,
cache: &State<RouteCache>,
) -> FallibleApiResponse {
use_api_cache!("album_route", album_id, cache);
let album = lib
.get_album_by_id(album_id)
.await
@ -69,5 +89,13 @@ pub async fn album_route(album_id: &str, lib: &State<Libary>) -> FallibleApiResp
.unwrap()
.insert("tracks".into(), tracks.into());
cache
.insert(
"album_route",
album_id,
serde_json::to_string(&album).unwrap(),
)
.await;
Ok(album)
}

View file

@ -7,6 +7,7 @@ use mongod::Model;
use mongodb::bson::doc;
use rocket::*;
use crate::cache::RouteCache;
use crate::library::artist::Artist;
use crate::library::Libary;
@ -18,9 +19,14 @@ pub async fn artists_route(lib: &State<Libary>) -> FallibleApiResponse {
}
#[get("/artist/<id>/image")]
pub async fn artist_image_route(id: &str) -> Option<NamedFile> {
let image = Artist::get_image_of(id).await?;
NamedFile::open(image).await.ok()
pub async fn artist_image_route(id: &str, cache: &State<RouteCache>) -> Option<NamedFile> {
let image = cache
.get_option("artist_image_route", id, || async {
Artist::get_image_of(id).await
})
.await;
NamedFile::open(image?).await.ok()
}
#[get("/artist/<id>")]