calckey/packages/backend/native-utils/src/model/repository.rs

34 lines
886 B
Rust
Raw Normal View History

2023-05-25 12:55:20 +00:00
pub mod antenna;
use async_trait::async_trait;
use schemars::JsonSchema;
2023-06-02 12:48:12 +00:00
use super::error::Error;
2023-05-25 12:55:20 +00:00
2023-06-02 15:55:14 +00:00
/// Repositories have a packer that converts a database model to its
/// corresponding API schema.
2023-05-25 12:55:20 +00:00
#[async_trait]
2023-05-27 09:50:07 +00:00
pub trait Repository<T: JsonSchema> {
2023-05-25 12:55:20 +00:00
async fn pack(self) -> Result<T, Error>;
2023-06-02 15:55:14 +00:00
/// Retrieves one model by its id and pack it.
2023-06-02 08:34:49 +00:00
async fn pack_by_id(id: String) -> Result<T, Error>;
}
mod macros {
2023-06-02 15:55:14 +00:00
/// Provides the default implementation of
/// [crate::model::repository::Repository::pack_by_id].
2023-06-02 08:34:49 +00:00
macro_rules! impl_pack_by_id {
($a:ty, $b:ident) => {
2023-06-02 12:48:12 +00:00
match <$a>::find_by_id($b)
.one(crate::database::get_database()?)
.await?
{
2023-06-02 08:34:49 +00:00
None => Err(Error::NotFound),
Some(m) => m.pack().await,
}
};
}
pub(crate) use impl_pack_by_id;
2023-05-25 12:55:20 +00:00
}