2022-08-08 01:51:31 +00:00

143 lines
3.3 KiB
Rust

//!
//!
use super::{models, schema::sites};
use beteran_common_rust as bcr;
use diesel::prelude::*;
use diesel::result::Error;
///
pub struct Repository {}
impl std::fmt::Debug for Repository {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Repository of sites").finish()
}
}
impl Default for Repository {
fn default() -> Self {
Self::new()
}
}
impl Repository {
///
pub fn new() -> Repository {
Repository {}
}
///
pub fn select(&self, conn: &diesel::PgConnection, id: uuid::Uuid) -> Result<models::Site, Error> {
sites::table
.find(id as uuid::Uuid)
.first::<models::Site>(conn)
}
///
pub fn select_by_url(
&self,
conn: &diesel::PgConnection,
url: &str,
) -> Result<Option<models::Site>, Error> {
use sites::dsl;
match sites::table
.filter(dsl::url.eq(url))
.first::<models::Site>(conn)
{
Ok(m) => Ok(Some(m)),
Err(e) => match e {
diesel::result::Error::NotFound => Ok(None),
_ => Err(e),
},
}
}
///
pub fn select_all_count(
&self,
conn: &diesel::PgConnection,
find_all: models::FindAll,
) -> Result<i64, Error> {
let mut q = sites::table.into_boxed();
if let Some(sp) = find_all.show {
q = q.filter(sites::dsl::show.eq(sp));
}
if let Some(sp) = find_all.can_use {
q = q.filter(sites::dsl::can_use.eq(sp));
}
if let Some(sp) = find_all.url_like {
q = q.filter(sites::dsl::url.like(sp));
}
q.count().get_result(conn)
}
///
pub fn select_all(
&self,
conn: &diesel::PgConnection,
find_all: models::FindAll,
) -> Result<Vec<models::Site>, Error> {
let mut q = sites::table.into_boxed();
if let Some(sp) = find_all.show {
q = q.filter(sites::dsl::show.eq(sp));
}
if let Some(sp) = find_all.can_use {
q = q.filter(sites::dsl::can_use.eq(sp));
}
if let Some(sp) = find_all.url_like {
q = q.filter(sites::dsl::url.like(sp));
}
if let Some(p) = find_all.pagination {
let page = p.page.unwrap_or(1);
if let Some(page_size) = p.page_size {
q = q.offset(((page - 1) * page_size) as i64);
q = q.limit(page_size as i64);
}
}
if let Some(orderbys) = find_all.sorts {
for s in orderbys {
match s {
bcr::models::pagination::Sort::ASC(property) => match property.as_str() {
"url" => {
q = q.order_by(sites::url.asc());
}
"created_at" => {
q = q.order_by(sites::created_at.asc());
}
"updated_at" => {
q = q.order_by(sites::updated_at.asc());
}
"deleted_at" => {
q = q.order_by(sites::deleted_at.asc());
}
_ => {}
},
bcr::models::pagination::Sort::DESC(property) => match property.as_str() {
"url" => {
q = q.order_by(sites::url.desc());
}
"created_at" => {
q = q.order_by(sites::created_at.desc());
}
"updated_at" => {
q = q.order_by(sites::updated_at.desc());
}
"deleted_at" => {
q = q.order_by(sites::deleted_at.desc());
}
_ => {}
},
};
}
}
q.load::<models::Site>(conn)
}
}