This repository has been archived on 2021-10-25. You can view files and clone it, but cannot push or open issues/pull-requests.
rusty-bever/src/db/sections.rs

77 lines
1.9 KiB
Rust
Raw Normal View History

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-10-10 15:46:19 +02:00
.load(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)
2021-10-10 15:46:19 +02:00
.get_result(conn)
2021-09-26 19:02:17 +02:00
.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)
2021-10-10 15:46:19 +02:00
.get_result(conn)
2021-09-26 19:02:17 +02:00
.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(())
}