Wrote some database boilerplate

sections-backend
Jef Roosens 2021-09-13 17:35:06 +02:00
parent 211e31a008
commit 8534090f0f
Signed by: Jef Roosens
GPG Key ID: 955C0660072F691F
4 changed files with 93 additions and 2 deletions

View File

@ -1,5 +1,8 @@
pub mod tokens;
pub mod users;
pub mod sections;
pub mod posts;
pub use tokens::{NewRefreshToken, RefreshToken};
pub use users::{NewUser, User};
pub use sections::{Section, NewSection};

44
src/db/posts.rs 100644
View File

@ -0,0 +1,44 @@
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
use uuid::Uuid;
use chrono::NaiveDate;
use crate::{
errors::{RbError, RbResult},
schema::{posts, posts::dsl::*},
};
#[derive(Queryable)]
pub struct Post
{
pub id: Uuid,
pub section_id: Uuid,
pub title: Option<String>,
pub publish_date: NaiveDate,
pub content: String,
}
#[derive(Insertable)]
#[table_name = "posts"]
pub struct NewPost
{
pub section_id: Uuid,
pub title: Option<String>,
pub publish_date: NaiveDate,
}
pub fn all(conn: &PgConnection) -> RbResult<Vec<Post>>
{
posts.load::<Post>(conn).map_err(|_| RbError::DbError("Couldn't get all posts."))
}
pub fn create(conn: &PgConnection, new_post: &NewPost) -> RbResult<()>
{
insert_into(posts)
.values(new_post)
.execute(conn)
.map_err(|_| RbError::DbError("Couldn't insert post."))?;
// TODO check for conflict?
Ok(())
}

44
src/db/sections.rs 100644
View File

@ -0,0 +1,44 @@
use diesel::{insert_into, prelude::*, Insertable, PgConnection, Queryable};
use uuid::Uuid;
use crate::{
errors::{RbError, RbResult},
schema::{sections, sections::dsl::*},
};
#[derive(Queryable)]
pub struct Section
{
pub id: Uuid,
pub title: String,
pub description: Option<String>,
pub is_default: bool,
pub has_titles: bool,
}
#[derive(Insertable)]
#[table_name = "sections"]
pub struct NewSection
{
title: String,
description: Option<String>,
is_default: bool,
has_titles: bool,
}
pub fn all(conn: &PgConnection) -> RbResult<Vec<Section>>
{
sections.load::<Section>(conn).map_err(|_| RbError::DbError("Couldn't get all sections"))
}
pub fn create(conn: &PgConnection, new_section: &NewSection) -> RbResult<()>
{
insert_into(sections)
.values(new_section)
.execute(conn)
.map_err(|_| RbError::DbError("Couldn't insert section."))?;
// TODO check for conflict?
Ok(())
}

View File

@ -36,7 +36,7 @@ pub fn create(conn: &PgConnection, new_refresh_token: &NewRefreshToken) -> RbRes
insert_into(refresh_tokens)
.values(new_refresh_token)
.execute(conn)
.map_err(|_| RbError::Custom("Couldn't insert refresh token."))?;
.map_err(|_| RbError::DbError("Couldn't insert refresh token."))?;
// TODO check for conflict?
@ -53,7 +53,7 @@ pub fn find_with_user(
.inner_join(crate::schema::users::dsl::users)
.filter(token.eq(token_val))
.first::<(RefreshToken, super::users::User)>(conn)
.map_err(|_| RbError::Custom("Couldn't get refresh token & user."))
.map_err(|_| RbError::DbError("Couldn't get refresh token & user."))
.ok()
}