From 5cc05beca3010fa5e434db5cc8d3e4e6f20063f4 Mon Sep 17 00:00:00 2001 From: ToBinio Date: Wed, 13 May 2026 09:37:47 +0200 Subject: [PATCH] extract backend into multiple crates --- Cargo.lock | 28 +++++++++- Cargo.toml | 2 +- api/Cargo.toml | 4 +- api/justfile | 2 +- api/orm/Cargo.toml | 9 ++++ api/{ => orm}/src/entities/category.rs | 0 api/{ => orm}/src/entities/check.rs | 0 api/{ => orm}/src/entities/mod.rs | 0 api/{ => orm}/src/entities/prelude.rs | 0 api/{ => orm}/src/entities/tag.rs | 0 api/{ => orm}/src/entities/time.rs | 0 api/{ => orm}/src/entities/todo.rs | 0 api/{ => orm}/src/entities/todo_tag.rs | 0 .../src/entities/web_push_subscription.rs | 0 api/orm/src/lib.rs | 22 ++++++++ api/services/Cargo.toml | 20 +++++++ .../services => services/src}/categories.rs | 54 ++++++------------- api/{src/services => services/src}/events.rs | 6 ++- .../services/mod.rs => services/src/lib.rs} | 5 ++ api/{src/services => services/src}/tags.rs | 49 ++++++----------- api/{src/services => services/src}/todos.rs | 45 +++++++--------- api/{src/services => services/src}/webpush.rs | 6 +-- api/src/auth.rs | 6 +-- api/src/jobs/web_push_notifications.rs | 12 ++--- api/src/lib.rs | 32 ++--------- api/src/routes/categories.rs | 6 +-- api/src/routes/tags.rs | 7 +-- api/src/routes/todo.rs | 11 ++-- api/src/routes/webpush.rs | 8 ++- api/tests/common/client.rs | 14 ++++- 30 files changed, 180 insertions(+), 168 deletions(-) create mode 100644 api/orm/Cargo.toml rename api/{ => orm}/src/entities/category.rs (100%) rename api/{ => orm}/src/entities/check.rs (100%) rename api/{ => orm}/src/entities/mod.rs (100%) rename api/{ => orm}/src/entities/prelude.rs (100%) rename api/{ => orm}/src/entities/tag.rs (100%) rename api/{ => orm}/src/entities/time.rs (100%) rename api/{ => orm}/src/entities/todo.rs (100%) rename api/{ => orm}/src/entities/todo_tag.rs (100%) rename api/{ => orm}/src/entities/web_push_subscription.rs (100%) create mode 100644 api/orm/src/lib.rs create mode 100644 api/services/Cargo.toml rename api/{src/services => services/src}/categories.rs (68%) rename api/{src/services => services/src}/events.rs (85%) rename api/{src/services/mod.rs => services/src/lib.rs} (55%) rename api/{src/services => services/src}/tags.rs (69%) rename api/{src/services => services/src}/todos.rs (94%) rename api/{src/services => services/src}/webpush.rs (95%) diff --git a/Cargo.lock b/Cargo.lock index 286c6ce..7cb62b6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -184,11 +184,11 @@ dependencies = [ "futures", "http 1.4.0", "jsonwebtoken", - "migration", + "orm", "reqwest 0.13.2", - "sea-orm", "serde", "serde_json", + "services", "thiserror 2.0.18", "tokio", "tokio-stream", @@ -2955,6 +2955,14 @@ dependencies = [ "num-traits", ] +[[package]] +name = "orm" +version = "0.1.0" +dependencies = [ + "migration", + "sea-orm", +] + [[package]] name = "ouroboros" version = "0.18.5" @@ -4211,6 +4219,22 @@ dependencies = [ "serde", ] +[[package]] +name = "services" +version = "0.1.0" +dependencies = [ + "chrono", + "orm", + "sea-orm", + "serde", + "thiserror 2.0.18", + "tokio", + "tracing", + "types", + "uuid", + "web-push", +] + [[package]] name = "sha1" version = "0.10.6" diff --git a/Cargo.toml b/Cargo.toml index fc10cc0..09032c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,3 @@ [workspace] resolver = "3" -members = ["api", "api/migration","libs/client", "libs/types","rpi-checker"] +members = ["api", "api/migration", "api/services", "api/orm","libs/client", "libs/types","rpi-checker"] diff --git a/api/Cargo.toml b/api/Cargo.toml index 3b57936..ff0c927 100644 --- a/api/Cargo.toml +++ b/api/Cargo.toml @@ -5,7 +5,8 @@ edition = "2024" [dependencies] types = { path = "../libs/types" } -migration = { path = "./migration" } +orm = { path = "./orm" } +services = { path = "./services" } dotenvy = "0.15.7" http = "1.4.0" @@ -20,7 +21,6 @@ tracing-subscriber = "0.3.23" thiserror = "2.0.18" color-eyre = "0.6.5" -sea-orm = { version = "1.1.20", features = ["debug-print", "runtime-tokio", "sqlx-sqlite"] } futures = "0.3.32" tokio = { version = "1.52.1", features = ["fs", "macros", "rt-multi-thread", "signal"] } diff --git a/api/justfile b/api/justfile index 801bb51..20ee558 100644 --- a/api/justfile +++ b/api/justfile @@ -1,5 +1,5 @@ generate_entities: - sea-orm-cli generate entity -u sqlite://../.data/storage.sqlite?mode=rwc -o src/entities + sea-orm-cli generate entity -u sqlite://../.data/storage.sqlite?mode=rwc -o orm/src/entities generate_migration name: sea-orm-cli migrate generate {{ name }} diff --git a/api/orm/Cargo.toml b/api/orm/Cargo.toml new file mode 100644 index 0000000..b17899e --- /dev/null +++ b/api/orm/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "orm" +version = "0.1.0" +edition = "2024" + +[dependencies] +migration = { path = "../migration" } + +sea-orm = { version = "1.1.20", features = ["debug-print", "runtime-tokio", "sqlx-sqlite"] } diff --git a/api/src/entities/category.rs b/api/orm/src/entities/category.rs similarity index 100% rename from api/src/entities/category.rs rename to api/orm/src/entities/category.rs diff --git a/api/src/entities/check.rs b/api/orm/src/entities/check.rs similarity index 100% rename from api/src/entities/check.rs rename to api/orm/src/entities/check.rs diff --git a/api/src/entities/mod.rs b/api/orm/src/entities/mod.rs similarity index 100% rename from api/src/entities/mod.rs rename to api/orm/src/entities/mod.rs diff --git a/api/src/entities/prelude.rs b/api/orm/src/entities/prelude.rs similarity index 100% rename from api/src/entities/prelude.rs rename to api/orm/src/entities/prelude.rs diff --git a/api/src/entities/tag.rs b/api/orm/src/entities/tag.rs similarity index 100% rename from api/src/entities/tag.rs rename to api/orm/src/entities/tag.rs diff --git a/api/src/entities/time.rs b/api/orm/src/entities/time.rs similarity index 100% rename from api/src/entities/time.rs rename to api/orm/src/entities/time.rs diff --git a/api/src/entities/todo.rs b/api/orm/src/entities/todo.rs similarity index 100% rename from api/src/entities/todo.rs rename to api/orm/src/entities/todo.rs diff --git a/api/src/entities/todo_tag.rs b/api/orm/src/entities/todo_tag.rs similarity index 100% rename from api/src/entities/todo_tag.rs rename to api/orm/src/entities/todo_tag.rs diff --git a/api/src/entities/web_push_subscription.rs b/api/orm/src/entities/web_push_subscription.rs similarity index 100% rename from api/src/entities/web_push_subscription.rs rename to api/orm/src/entities/web_push_subscription.rs diff --git a/api/orm/src/lib.rs b/api/orm/src/lib.rs new file mode 100644 index 0000000..5a8cd83 --- /dev/null +++ b/api/orm/src/lib.rs @@ -0,0 +1,22 @@ +use migration::{Migrator, MigratorTrait}; +use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseConnection, DbErr}; + +pub mod entities; + +pub type OrmConnection = DatabaseConnection; + +pub async fn init_db(url: &str) -> Result { + let mut options = ConnectOptions::new(url); + options.sqlx_logging(false); + + let connection = Database::connect(options).await?; + + let connection = match connection.get_database_backend() { + sea_orm::DatabaseBackend::Sqlite => connection, + _ => panic!("Unsupported database backend"), + }; + + Migrator::up(&connection, None).await?; + + Ok(connection) +} diff --git a/api/services/Cargo.toml b/api/services/Cargo.toml new file mode 100644 index 0000000..bfdcff3 --- /dev/null +++ b/api/services/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "services" +version = "0.1.0" +edition = "2024" + +[dependencies] +orm = { path = "../orm" } +types = { path = "../../libs/types" } + +tokio = { version = "1.52.1", features = ["fs", "macros", "rt-multi-thread", "signal"] } +sea-orm = { version = "1.1.20", features = ["debug-print", "runtime-tokio", "sqlx-sqlite"] } + +serde = { version = "1.0.228", features = ["derive"] } +tracing = "0.1.44" + +thiserror = "2.0.18" +uuid = { version = "1.23.1", features = ["v4"] } + +chrono = { version = "0.4.42", features = ["serde"] } +web-push = { version = "0.11.0", default-features = false, features = ["hyper-client"] } diff --git a/api/src/services/categories.rs b/api/services/src/categories.rs similarity index 68% rename from api/src/services/categories.rs rename to api/services/src/categories.rs index b1ff96e..4c35355 100644 --- a/api/src/services/categories.rs +++ b/api/services/src/categories.rs @@ -1,15 +1,15 @@ -use crate::{ - auth::User, +use orm::{ + OrmConnection, entities::{category, prelude::*}, }; -use sea_orm::{ - ActiveValue::Set, ColumnTrait, DatabaseConnection, DeleteResult, EntityTrait, QueryFilter, -}; +use sea_orm::{ActiveValue::Set, ColumnTrait, DeleteResult, EntityTrait, QueryFilter}; use thiserror::Error; use types::{Category as CategoryModel, HexColor}; use uuid::Uuid; +use crate::User; + #[derive(Error, Debug, PartialEq)] pub enum CategoryServiceError { #[error("database error - caused by: {0}")] @@ -24,22 +24,19 @@ pub struct CategoryService; impl CategoryService { pub async fn get_all( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, ) -> Result, CategoryServiceError> { let categories = Category::find() .filter(category::Column::OwnerId.eq(user.id.clone())) .all(db) .await?; - categories - .into_iter() - .map(|category| category.try_into()) - .collect() + categories.into_iter().map(Self::to_category_dto).collect() } pub async fn get_by_id( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, category_id: Uuid, ) -> Result, CategoryServiceError> { let category = Category::find_by_id(category_id) @@ -47,12 +44,12 @@ impl CategoryService { .one(db) .await?; - category.map(|category| category.try_into()).transpose() + category.map(Self::to_category_dto).transpose() } pub async fn delete_by_id( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, category_id: Uuid, ) -> Result { let category = Category::delete_by_id(category_id) @@ -65,7 +62,7 @@ impl CategoryService { pub async fn create( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, category: CategoryModel, ) -> Result { let category = Category::insert(category::ActiveModel { @@ -78,12 +75,12 @@ impl CategoryService { .exec_with_returning(db) .await?; - category.try_into() + Self::to_category_dto(category) } pub async fn update( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, category: CategoryModel, ) -> Result { let category = Category::update(category::ActiveModel { @@ -97,31 +94,10 @@ impl CategoryService { .exec(db) .await?; - category.try_into() - } -} - -impl TryFrom for CategoryModel { - type Error = CategoryServiceError; - - fn try_from(value: category::Model) -> Result { - let category = CategoryModel { - uuid: value.id, - name: value.name.to_string(), - color: HexColor::from_text(&value.color).ok_or( - CategoryServiceError::InvalidCategory("invalid color".to_string()), - )?, - icon: value.icon.to_string(), - }; - - Ok(category) + Self::to_category_dto(category) } -} - -impl TryFrom<&category::Model> for CategoryModel { - type Error = CategoryServiceError; - fn try_from(value: &category::Model) -> Result { + fn to_category_dto(value: category::Model) -> Result { let category = CategoryModel { uuid: value.id, name: value.name.to_string(), diff --git a/api/src/services/events.rs b/api/services/src/events.rs similarity index 85% rename from api/src/services/events.rs rename to api/services/src/events.rs index fdeb380..c2b0364 100644 --- a/api/src/services/events.rs +++ b/api/services/src/events.rs @@ -12,12 +12,14 @@ pub struct EventService { tx: broadcast::Sender, } -impl EventService { - pub fn new() -> Self { +impl Default for EventService { + fn default() -> Self { let tx = broadcast::Sender::new(64); Self { tx } } +} +impl EventService { pub fn broadcast(&self, event: Event) { let _ = self.tx.send(event); } diff --git a/api/src/services/mod.rs b/api/services/src/lib.rs similarity index 55% rename from api/src/services/mod.rs rename to api/services/src/lib.rs index 1661943..b6ab1e7 100644 --- a/api/src/services/mod.rs +++ b/api/services/src/lib.rs @@ -3,3 +3,8 @@ pub mod events; pub mod tags; pub mod todos; pub mod webpush; + +#[derive(Clone, Debug)] +pub struct User { + pub id: String, +} diff --git a/api/src/services/tags.rs b/api/services/src/tags.rs similarity index 69% rename from api/src/services/tags.rs rename to api/services/src/tags.rs index dc527fe..edbf188 100644 --- a/api/src/services/tags.rs +++ b/api/services/src/tags.rs @@ -1,15 +1,15 @@ -use crate::{ - auth::User, +use orm::{ + OrmConnection, entities::{prelude::*, tag}, }; -use sea_orm::{ - ActiveValue::Set, ColumnTrait, DatabaseConnection, DeleteResult, EntityTrait, QueryFilter, -}; +use sea_orm::{ActiveValue::Set, ColumnTrait, DeleteResult, EntityTrait, QueryFilter}; use thiserror::Error; use types::{HexColor, Tag as TagModel}; use uuid::Uuid; +use crate::User; + #[derive(Error, Debug, PartialEq)] pub enum TagServiceError { #[error("database error - caused by: {0}")] @@ -24,19 +24,19 @@ pub struct TagService; impl TagService { pub async fn get_all( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, ) -> Result, TagServiceError> { let tags = Tag::find() .filter(tag::Column::OwnerId.eq(user.id.clone())) .all(db) .await?; - tags.into_iter().map(|tag| tag.try_into()).collect() + tags.into_iter().map(Self::to_tag_dto).collect() } pub async fn get_by_id( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, tag_id: Uuid, ) -> Result, TagServiceError> { let tag = Tag::find_by_id(tag_id) @@ -44,12 +44,12 @@ impl TagService { .one(db) .await?; - tag.map(|tag| tag.try_into()).transpose() + tag.map(Self::to_tag_dto).transpose() } pub async fn delete_by_id( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, tag_id: Uuid, ) -> Result { let tag = Tag::delete_by_id(tag_id) @@ -62,7 +62,7 @@ impl TagService { pub async fn create( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, tag: TagModel, ) -> Result { let tag = Tag::insert(tag::ActiveModel { @@ -74,12 +74,12 @@ impl TagService { .exec_with_returning(db) .await?; - tag.try_into() + Self::to_tag_dto(tag) } pub async fn update( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, tag: TagModel, ) -> Result { let tag = Tag::update(tag::ActiveModel { @@ -92,14 +92,10 @@ impl TagService { .exec(db) .await?; - tag.try_into() + Self::to_tag_dto(tag) } -} - -impl TryFrom for TagModel { - type Error = TagServiceError; - fn try_from(value: tag::Model) -> Result { + fn to_tag_dto(value: tag::Model) -> Result { let tag = TagModel { uuid: value.id, name: value.name, @@ -110,18 +106,3 @@ impl TryFrom for TagModel { Ok(tag) } } - -impl TryFrom<&tag::Model> for TagModel { - type Error = TagServiceError; - - fn try_from(value: &tag::Model) -> Result { - let tag = TagModel { - uuid: value.id, - name: value.name.clone(), - color: HexColor::from_text(&value.color) - .ok_or(TagServiceError::InvalidTag("invalid color".to_string()))?, - }; - - Ok(tag) - } -} diff --git a/api/src/services/todos.rs b/api/services/src/todos.rs similarity index 94% rename from api/src/services/todos.rs rename to api/services/src/todos.rs index 9b87b17..6280430 100644 --- a/api/src/services/todos.rs +++ b/api/services/src/todos.rs @@ -1,11 +1,12 @@ use std::collections::{HashMap, HashSet}; use chrono::{Local, NaiveDate, NaiveDateTime}; -use migration::Expr; +use orm::OrmConnection; use sea_orm::ActiveValue::{NotSet, Set}; +use sea_orm::sea_query::Expr; use sea_orm::{ - ColumnTrait, ConnectionTrait, DatabaseConnection, DeleteResult, EntityTrait, IntoActiveModel, - ModelTrait, PaginatorTrait, QueryFilter, QueryOrder, TransactionTrait, + ColumnTrait, ConnectionTrait, DeleteResult, EntityTrait, IntoActiveModel, ModelTrait, + PaginatorTrait, QueryFilter, QueryOrder, TransactionTrait, }; use serde::Deserialize; use thiserror::Error; @@ -13,8 +14,8 @@ use tracing::warn; use types::{Time as TimeModel, TimeRange, TimeRecurring, Todo as TodoModel}; use uuid::Uuid; -use crate::auth::User; -use crate::entities::{check, prelude::*, time, todo, todo_tag}; +use crate::User; +use orm::entities::{check, prelude::*, time, todo, todo_tag}; #[derive(Error, Debug, PartialEq)] pub enum TodoServiceError { @@ -40,7 +41,7 @@ pub struct TodoService; impl TodoService { pub async fn get_all( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, ) -> Result, TodoServiceError> { let todos = Todo::find() .filter(todo::Column::OwnerId.eq(user.id.clone())) @@ -77,7 +78,7 @@ impl TodoService { .into_iter() .fold(HashMap::new(), |mut acc, time| { let todo = time.todo_id; - match time.try_into() { + match Self::to_time_dto(time) { Ok(time_model) => { acc.entry(todo).or_default().push(time_model); } @@ -115,7 +116,7 @@ impl TodoService { } pub async fn get_in_time_range( - db: &DatabaseConnection, + db: &OrmConnection, start: NaiveDateTime, end: NaiveDateTime, ) -> Result, TodoServiceError> { @@ -170,7 +171,7 @@ impl TodoService { uuid: todo.id, title: todo.title.to_string(), note: todo.note.to_string(), - time: time.map(|time| time.try_into()).transpose()?, + time: time.map(Self::to_time_dto).transpose()?, tags: tags.iter().map(|tag| tag.tag_id).collect(), category: todo.category_id, checks: checks.iter().map(|check| check.date).collect(), @@ -179,7 +180,7 @@ impl TodoService { pub async fn create( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, todo: TodoModel, positon: TodoPosition, reference: Option, @@ -237,7 +238,7 @@ impl TodoService { } if let Some(time) = todo.time { - let mut time_model = time::ActiveModel::from(time); + let mut time_model = Self::to_time_model(time); time_model.todo_id = Set(todo.uuid); Time::insert(time_model).exec(db).await?; @@ -252,7 +253,7 @@ impl TodoService { pub async fn update( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, todo: TodoModel, ) -> Result { let tx = db.begin().await?; @@ -300,7 +301,7 @@ impl TodoService { let has_time = Time::find_by_id(todo.uuid).exists(&tx).await?; if let Some(time) = todo.time { - let mut time_model: time::ActiveModel = time.into(); + let mut time_model: time::ActiveModel = Self::to_time_model(time); time_model.todo_id = Set(todo.uuid); if has_time { @@ -323,7 +324,7 @@ impl TodoService { pub async fn delete_by_id( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, id: Uuid, ) -> Result { let todo = Todo::delete_by_id(id) @@ -336,7 +337,7 @@ impl TodoService { pub async fn add_check( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, id: Uuid, ) -> Result, TodoServiceError> { if Self::get_by_id(user, db, id).await?.is_none() { @@ -355,7 +356,7 @@ impl TodoService { pub async fn remove_check( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, id: Uuid, ) -> Result, TodoServiceError> { let tx = db.begin().await?; @@ -385,7 +386,7 @@ impl TodoService { pub async fn move_todo( user: &User, - db: &DatabaseConnection, + db: &OrmConnection, todo: Uuid, target: Uuid, ) -> Result<(), TodoServiceError> { @@ -436,10 +437,8 @@ impl TodoService { tx.commit().await?; Ok(()) } -} -impl From for time::ActiveModel { - fn from(value: TimeModel) -> Self { + fn to_time_model(value: TimeModel) -> time::ActiveModel { match value { types::Time::Range { inner } => time::ActiveModel { format: Set("range".to_string()), @@ -468,12 +467,8 @@ impl From for time::ActiveModel { }, } } -} - -impl TryFrom for TimeModel { - type Error = TodoServiceError; - fn try_from(value: time::Model) -> Result { + fn to_time_dto(value: time::Model) -> Result { let time = match value.format.as_str() { "range" => types::Time::Range { inner: TimeRange { diff --git a/api/src/services/webpush.rs b/api/services/src/webpush.rs similarity index 95% rename from api/src/services/webpush.rs rename to api/services/src/webpush.rs index 3353217..3a189f2 100644 --- a/api/src/services/webpush.rs +++ b/api/services/src/webpush.rs @@ -5,10 +5,8 @@ use sea_orm::{ use thiserror::Error; use web_push::SubscriptionInfo; -use crate::{ - auth::User, - entities::{prelude::*, web_push_subscription}, -}; +use crate::User; +use orm::entities::{prelude::*, web_push_subscription}; #[derive(Error, Debug, PartialEq)] pub enum WebPushServiceError { diff --git a/api/src/auth.rs b/api/src/auth.rs index bce96be..c21e61f 100644 --- a/api/src/auth.rs +++ b/api/src/auth.rs @@ -8,16 +8,12 @@ use axum_extra::{ use http::{StatusCode, request::Parts}; use jsonwebtoken::{DecodingKey, jwk::JwkSet}; use serde::Deserialize; +use services::User; use tokio::sync::RwLock; use tracing::{info, warn}; use crate::AppState; -#[derive(Clone, Debug)] -pub struct User { - pub id: String, -} - #[derive(Clone, Debug, Deserialize)] struct Claims { id: String, diff --git a/api/src/jobs/web_push_notifications.rs b/api/src/jobs/web_push_notifications.rs index bfae64e..b1243ee 100644 --- a/api/src/jobs/web_push_notifications.rs +++ b/api/src/jobs/web_push_notifications.rs @@ -1,5 +1,5 @@ use chrono::{NaiveDateTime, Timelike}; -use sea_orm::DatabaseConnection; +use orm::OrmConnection; use serde_json::json; use std::time::Duration; use tokio::time; @@ -10,10 +10,8 @@ use web_push::{ WebPushMessageBuilder, }; -use crate::{ - AppState, - services::{todos::TodoService, webpush::WebPushService}, -}; +use crate::AppState; +use services::{todos::TodoService, webpush::WebPushService}; pub async fn run_web_push_job(state: AppState) { tokio::spawn(async move { @@ -48,7 +46,7 @@ fn get_next_time_window() -> Result<(NaiveDateTime, NaiveDateTime), String> { Ok((start, end)) } -async fn send_notifications(db: &DatabaseConnection, web_push_key: &str) -> Result<(), String> { +async fn send_notifications(db: &OrmConnection, web_push_key: &str) -> Result<(), String> { let (start, end) = get_next_time_window()?; let todos = TodoService::get_in_time_range(db, start, end) @@ -67,7 +65,7 @@ async fn send_notifications(db: &DatabaseConnection, web_push_key: &str) -> Resu async fn send_notifications_for_todo( todo: &Todo, owner_id: &str, - db: &DatabaseConnection, + db: &OrmConnection, web_push_key: &str, ) -> Result<(), String> { let subscriptions = WebPushService::get_all_by_owner_id(db, owner_id) diff --git a/api/src/lib.rs b/api/src/lib.rs index 9f3a4c2..c18c3ad 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -3,29 +3,23 @@ use axum::Router; use color_eyre::eyre; use http::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}; -use migration::{Migrator, MigratorTrait}; -use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseConnection}; +use orm::{OrmConnection, init_db}; use tower::ServiceBuilder; use tower_http::{ cors::{Any, CorsLayer}, trace::TraceLayer, }; -use crate::{ - auth::{JwksCache, User}, - jobs::web_push_notifications::run_web_push_job, - services::events::EventService, -}; +use crate::{auth::JwksCache, jobs::web_push_notifications::run_web_push_job}; +use services::{User, events::EventService}; pub mod auth; -mod entities; mod jobs; mod routes; -mod services; #[derive(Clone)] struct AppState { - db_connection: DatabaseConnection, + db_connection: OrmConnection, event_service: EventService, test_user: Option, constants: Constants, @@ -48,7 +42,7 @@ pub async fn app( ) -> eyre::Result { let state = AppState { db_connection: init_db(db_url).await?, - event_service: EventService::new(), + event_service: EventService::default(), test_user, constants: Constants { web_push_key, @@ -76,19 +70,3 @@ pub async fn app( Ok(app) } - -async fn init_db(url: &str) -> eyre::Result { - let mut options = ConnectOptions::new(url); - options.sqlx_logging(false); - - let connection = Database::connect(options).await?; - - let connection = match connection.get_database_backend() { - sea_orm::DatabaseBackend::Sqlite => connection, - _ => panic!("Unsupported database backend"), - }; - - Migrator::up(&connection, None).await?; - - Ok(connection) -} diff --git a/api/src/routes/categories.rs b/api/src/routes/categories.rs index 6a24df3..7152ec1 100644 --- a/api/src/routes/categories.rs +++ b/api/src/routes/categories.rs @@ -15,9 +15,9 @@ use tracing::warn; use types::Category as CategoryModel; use uuid::Uuid; -use crate::services::categories::{CategoryService, CategoryServiceError}; -use crate::services::events; -use crate::{AppState, auth::User}; +use crate::AppState; +use services::categories::{CategoryService, CategoryServiceError}; +use services::{User, events}; #[derive(Error, Debug, PartialEq)] enum ApiError { diff --git a/api/src/routes/tags.rs b/api/src/routes/tags.rs index b0aff46..2ffca27 100644 --- a/api/src/routes/tags.rs +++ b/api/src/routes/tags.rs @@ -15,9 +15,10 @@ use tracing::warn; use types::Tag as TagModel; use uuid::Uuid; -use crate::services::events::{self}; -use crate::services::tags::{TagService, TagServiceError}; -use crate::{AppState, auth::User}; +use crate::AppState; +use services::User; +use services::events::{self}; +use services::tags::{TagService, TagServiceError}; #[derive(Error, Debug, PartialEq)] enum ApiError { diff --git a/api/src/routes/todo.rs b/api/src/routes/todo.rs index 7bc815b..69e4c97 100644 --- a/api/src/routes/todo.rs +++ b/api/src/routes/todo.rs @@ -15,13 +15,10 @@ use tracing::warn; use types::Todo as TodoModel; use uuid::Uuid; -use crate::{ - AppState, - auth::User, - services::{ - events, - todos::{TodoPosition, TodoService, TodoServiceError}, - }, +use crate::AppState; +use services::{ + User, events, + todos::{TodoPosition, TodoService, TodoServiceError}, }; #[derive(Error, Debug, PartialEq)] diff --git a/api/src/routes/webpush.rs b/api/src/routes/webpush.rs index 845d894..bd67853 100644 --- a/api/src/routes/webpush.rs +++ b/api/src/routes/webpush.rs @@ -9,11 +9,9 @@ use thiserror::Error; use tracing::warn; use web_push::SubscriptionInfo; -use crate::{ - AppState, - auth::User, - services::webpush::{WebPushService, WebPushServiceError}, -}; +use crate::AppState; +use services::User; +use services::webpush::{WebPushService, WebPushServiceError}; #[derive(Error, Debug, PartialEq)] enum ApiError { diff --git a/api/tests/common/client.rs b/api/tests/common/client.rs index 5e15f51..48ccc47 100644 --- a/api/tests/common/client.rs +++ b/api/tests/common/client.rs @@ -1,7 +1,11 @@ #![allow(unused)] -use api::{app, auth::User}; +use std::sync::OnceLock; + +use api::app; use axum_test::{TestResponse, TestServer}; use serde::de::DeserializeOwned; +use services::User; +use tracing::Level; use types::{Category, Tag, Todo}; use uuid::Uuid; @@ -123,7 +127,15 @@ impl Client { } } +static TRACING: OnceLock<()> = OnceLock::new(); + pub async fn get_client() -> Client { + TRACING.get_or_init(|| { + tracing_subscriber::fmt() + .with_max_level(Level::DEBUG) + .init(); + }); + let user = User { id: Uuid::new_v4().to_string(), }; -- knotmirror 0.0.1