2021-09-13 17:35:06 +02:00
|
|
|
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
|
2021-09-26 19:02:17 +02:00
|
|
|
use serde::{Deserialize, Serialize};
|
2021-09-13 17:35:06 +02:00
|
|
|
use uuid::Uuid;
|
|
|
|
|
|
|
|
use crate::{
|
|
|
|
errors::{RbError, RbResult},
|
|
|
|
schema::{sections, sections::dsl::*},
|
|
|
|
};
|
|
|
|
|
2021-09-26 19:02:17 +02:00
|
|
|
#[derive(Queryable, Serialize)]
|
2021-09-13 17:35:06 +02:00
|
|
|
pub struct Section
|
|
|
|
{
|
|
|
|
pub id: Uuid,
|
|
|
|
pub title: String,
|
|
|
|
pub description: Option<String>,
|
|
|
|
pub is_default: bool,
|
|
|
|
pub has_titles: bool,
|
|
|
|
}
|
|
|
|
|
2021-09-13 22:15:38 +02:00
|
|
|
#[derive(Deserialize, Insertable)]
|
2021-09-13 17:35:06 +02:00
|
|
|
#[table_name = "sections"]
|
2021-09-23 15:30:39 +02:00
|
|
|
#[serde(rename_all = "camelCase")]
|
2021-09-13 17:35:06 +02:00
|
|
|
pub struct NewSection
|
|
|
|
{
|
|
|
|
title: String,
|
|
|
|
description: Option<String>,
|
2021-09-13 22:15:38 +02:00
|
|
|
is_default: Option<bool>,
|
|
|
|
has_titles: Option<bool>,
|
2021-09-13 17:35:06 +02:00
|
|
|
}
|
|
|
|
|
2021-09-26 19:02:17 +02:00
|
|
|
#[derive(Deserialize, AsChangeset)]
|
|
|
|
#[table_name = "sections"]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
pub struct PatchSection
|
|
|
|
{
|
|
|
|
title: Option<String>,
|
|
|
|
description: Option<String>,
|
|
|
|
is_default: Option<bool>,
|
|
|
|
has_titles: Option<bool>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn get(conn: &PgConnection, offset_: u32, limit_: u32) -> RbResult<Vec<Section>>
|
2021-09-13 17:35:06 +02:00
|
|
|
{
|
2021-09-26 19:02:17 +02:00
|
|
|
Ok(sections
|
|
|
|
.offset(offset_.into())
|
|
|
|
.limit(limit_.into())
|
2021-09-13 22:15:38 +02:00
|
|
|
.load::<Section>(conn)
|
2021-09-26 19:02:17 +02:00
|
|
|
.map_err(|_| RbError::DbError("Couldn't query sections."))?)
|
2021-09-13 17:35:06 +02:00
|
|
|
}
|
|
|
|
|
2021-09-26 19:02:17 +02:00
|
|
|
pub fn create(conn: &PgConnection, new_post: &NewSection) -> RbResult<Section>
|
2021-09-13 17:35:06 +02:00
|
|
|
{
|
2021-09-26 19:02:17 +02:00
|
|
|
Ok(insert_into(sections)
|
|
|
|
.values(new_post)
|
|
|
|
.get_result::<Section>(conn)
|
|
|
|
.map_err(|_| RbError::DbError("Couldn't insert section."))?)
|
2021-09-13 17:35:06 +02:00
|
|
|
|
|
|
|
// TODO check for conflict?
|
2021-09-26 19:02:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn update(conn: &PgConnection, post_id: &Uuid, patch_post: &PatchSection) -> RbResult<Section>
|
|
|
|
{
|
|
|
|
Ok(diesel::update(sections.filter(id.eq(post_id)))
|
|
|
|
.set(patch_post)
|
|
|
|
.get_result::<Section>(conn)
|
|
|
|
.map_err(|_| RbError::DbError("Couldn't update section."))?)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn delete(conn: &PgConnection, post_id: &Uuid) -> RbResult<()>
|
|
|
|
{
|
|
|
|
diesel::delete(sections.filter(id.eq(post_id)))
|
|
|
|
.execute(conn)
|
|
|
|
.map_err(|_| RbError::DbError("Couldn't delete section."))?;
|
2021-09-13 17:35:06 +02:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|