synthwave/src/route/mod.rs
2024-10-04 14:38:35 +02:00

63 lines
1.3 KiB
Rust

use std::str::FromStr;
use rocket::{
get,
response::{status::BadRequest, Redirect},
uri,
};
use serde_json::json;
pub mod admin;
pub mod album;
pub mod artist;
pub mod event;
pub mod playlist;
pub mod search;
pub mod track;
pub mod user;
// todo : rework api
/// A trait to generate a Model API representation in JSON format.
pub trait ToAPI: Sized {
/// Generate public API JSON
fn api(&self) -> impl std::future::Future<Output = serde_json::Value>;
}
/// Converts a slice of items implementing the `ToAPI` trait into a `Vec` of JSON values.
pub async fn vec_to_api(items: &[impl ToAPI]) -> Vec<serde_json::Value> {
let mut ret = Vec::with_capacity(items.len());
for e in items {
ret.push(e.api().await);
}
ret
}
pub fn to_uuid(id: &str) -> Result<uuid::Uuid, ApiError> {
uuid::Uuid::from_str(id).map_err(|_| no_uuid_error())
}
type ApiError = BadRequest<serde_json::Value>;
type FallibleApiResponse = Result<serde_json::Value, ApiError>;
pub fn no_uuid_error() -> ApiError {
api_error("No valid UUID")
}
pub fn api_error(msg: &str) -> ApiError {
BadRequest(json!({
"error": msg
}))
}
#[get("/")]
pub fn index_redir() -> Redirect {
Redirect::to(uri!("/web"))
}
#[get("/manifest.json")]
pub fn manifest_redir() -> Redirect {
Redirect::to(uri!("/web/manifest.json"))
}