feat: implement image db pagination
parent
51fa92ba3b
commit
39a15bb094
|
@ -7,6 +7,7 @@ use diesel::{
|
|||
SqliteConnection,
|
||||
};
|
||||
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
|
||||
use serde::Deserialize;
|
||||
|
||||
use std::{error::Error, fmt, path::Path};
|
||||
|
||||
|
@ -67,3 +68,19 @@ pub fn initialize_db(path: impl AsRef<Path>, run_migrations: bool) -> Result<DbP
|
|||
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Copy, Clone)]
|
||||
#[serde(default)]
|
||||
pub struct Pagination {
|
||||
page: u32,
|
||||
per_page: u32,
|
||||
}
|
||||
|
||||
impl Default for Pagination {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
page: 0,
|
||||
per_page: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ use chrono::NaiveDate;
|
|||
use diesel::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::db::{schema::*, DbPool, DbResult};
|
||||
use crate::db::{schema::*, DbPool, DbResult, Pagination};
|
||||
|
||||
#[derive(Serialize, Queryable, Selectable)]
|
||||
#[diesel(table_name = images)]
|
||||
|
@ -25,6 +25,11 @@ pub struct NewImage {
|
|||
note: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Copy)]
|
||||
pub struct ImageFilter {
|
||||
pub plant_id: Option<i32>,
|
||||
}
|
||||
|
||||
impl NewImage {
|
||||
pub fn new(
|
||||
plant_id: i32,
|
||||
|
@ -56,4 +61,18 @@ impl Image {
|
|||
.first(&mut pool.get()?)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn page(pool: &DbPool, page: Pagination, filter: ImageFilter) -> DbResult<Vec<Self>> {
|
||||
let mut query = images::table.select(Self::as_select()).into_boxed();
|
||||
|
||||
if let Some(plant_id) = filter.plant_id {
|
||||
query = query.filter(images::dsl::plant_id.eq(plant_id));
|
||||
}
|
||||
|
||||
Ok(query
|
||||
.order_by((images::dsl::date_taken.desc(), images::dsl::id.desc()))
|
||||
.offset((page.page * page.per_page).into())
|
||||
.limit(page.per_page.into())
|
||||
.get_results(&mut pool.get()?)?)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue