Modularize, Model trait, list_owners

This commit is contained in:
2020-07-18 17:46:33 -04:00
parent 6b1f31f246
commit 9ec7fc1518
10 changed files with 462 additions and 389 deletions

28
src/models/model.rs Normal file
View File

@@ -0,0 +1,28 @@
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use sqlx::postgres::PgPool;
use url::Url;
use super::ListParams;
#[async_trait]
pub trait Model
where
Self: std::marker::Sized,
{
fn resource_name() -> &'static str;
fn pk(&self) -> Option<i32>;
fn url(&self, api_url: &Url) -> Result<Url> {
if let Some(pk) = self.pk() {
Ok(api_url.join(&format!("/{}s/{}", Self::resource_name(), pk))?)
} else {
Err(anyhow!(
"Cannot get URL for {} with no primary key",
Self::resource_name()
))
}
}
async fn get(db: &PgPool, id: i32) -> Result<Self>;
async fn save(self, db: &PgPool) -> Result<Self>;
async fn list(db: &PgPool, list_params: ListParams) -> Result<Vec<Self>>;
}