Something went wrong. Try again.
A simple to-do app focused on tasks that can be completed within a specific time span. taskline.tobinio.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113use orm::{ OrmConnection, entities::{category, prelude::*},};
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}")] DbError(#[from] sea_orm::DbErr),
#[error("invalid category - caused by: {0}")] InvalidCategory(String),}
pub struct CategoryService;
impl CategoryService { pub async fn get_all( user: &User, db: &OrmConnection, ) -> Result<Vec<CategoryModel>, CategoryServiceError> { let categories = Category::find() .filter(category::Column::OwnerId.eq(user.id.clone())) .all(db) .await?;
categories.into_iter().map(Self::to_category_dto).collect() }
pub async fn get_by_id( user: &User, db: &OrmConnection, category_id: Uuid, ) -> Result<Option<CategoryModel>, CategoryServiceError> { let category = Category::find_by_id(category_id) .filter(category::Column::OwnerId.eq(user.id.clone())) .one(db) .await?;
category.map(Self::to_category_dto).transpose() }
pub async fn delete_by_id( user: &User, db: &OrmConnection, category_id: Uuid, ) -> Result<DeleteResult, CategoryServiceError> { let category = Category::delete_by_id(category_id) .filter(category::Column::OwnerId.eq(user.id.clone())) .exec(db) .await?;
Ok(category) }
pub async fn create( user: &User, db: &OrmConnection, category: CategoryModel, ) -> Result<CategoryModel, CategoryServiceError> { let category = Category::insert(category::ActiveModel { id: Set(category.uuid), owner_id: Set(user.id.clone()), name: Set(category.name), color: Set(category.color.as_str().to_string()), icon: Set(category.icon), }) .exec_with_returning(db) .await?;
Self::to_category_dto(category) }
pub async fn update( user: &User, db: &OrmConnection, category: CategoryModel, ) -> Result<CategoryModel, CategoryServiceError> { let category = Category::update(category::ActiveModel { id: Set(category.uuid), owner_id: Set(user.id.clone()), name: Set(category.name), color: Set(category.color.as_str().to_string()), icon: Set(category.icon), }) .filter(category::Column::OwnerId.eq(user.id.clone())) .exec(db) .await?;
Self::to_category_dto(category) }
fn to_category_dto(value: category::Model) -> Result<CategoryModel, CategoryServiceError> { 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) }}