2020-05-16 14:04:08 +00:00
|
|
|
use crate::{
|
|
|
|
schema::{category, category::dsl::*},
|
2020-07-10 18:15:41 +00:00
|
|
|
Crud,
|
2020-05-16 14:04:08 +00:00
|
|
|
};
|
|
|
|
use diesel::{dsl::*, result::Error, *};
|
2020-09-14 15:29:50 +00:00
|
|
|
use serde::Serialize;
|
2019-04-03 23:01:20 +00:00
|
|
|
|
2020-09-03 19:45:12 +00:00
|
|
|
#[derive(Queryable, Identifiable, PartialEq, Debug, Serialize)]
|
2019-09-07 15:35:05 +00:00
|
|
|
#[table_name = "category"]
|
2019-04-03 23:01:20 +00:00
|
|
|
pub struct Category {
|
|
|
|
pub id: i32,
|
2019-09-07 15:35:05 +00:00
|
|
|
pub name: String,
|
2019-04-03 23:01:20 +00:00
|
|
|
}
|
|
|
|
|
2020-09-03 19:45:12 +00:00
|
|
|
#[derive(Insertable, AsChangeset)]
|
2019-09-07 15:35:05 +00:00
|
|
|
#[table_name = "category"]
|
2019-04-03 23:01:20 +00:00
|
|
|
pub struct CategoryForm {
|
|
|
|
pub name: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Crud<CategoryForm> for Category {
|
|
|
|
fn read(conn: &PgConnection, category_id: i32) -> Result<Self, Error> {
|
2019-09-07 15:35:05 +00:00
|
|
|
category.find(category_id).first::<Self>(conn)
|
2019-04-03 23:01:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn create(conn: &PgConnection, new_category: &CategoryForm) -> Result<Self, Error> {
|
2019-09-07 15:35:05 +00:00
|
|
|
insert_into(category)
|
|
|
|
.values(new_category)
|
|
|
|
.get_result::<Self>(conn)
|
2019-04-03 23:01:20 +00:00
|
|
|
}
|
|
|
|
|
2019-09-07 15:35:05 +00:00
|
|
|
fn update(
|
|
|
|
conn: &PgConnection,
|
|
|
|
category_id: i32,
|
|
|
|
new_category: &CategoryForm,
|
|
|
|
) -> Result<Self, Error> {
|
2019-04-03 23:01:20 +00:00
|
|
|
diesel::update(category.find(category_id))
|
|
|
|
.set(new_category)
|
|
|
|
.get_result::<Self>(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Category {
|
|
|
|
pub fn list_all(conn: &PgConnection) -> Result<Vec<Self>, Error> {
|
|
|
|
category.load::<Self>(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2020-07-10 18:15:41 +00:00
|
|
|
use crate::{category::Category, tests::establish_unpooled_connection};
|
2020-05-16 14:04:08 +00:00
|
|
|
|
2019-09-07 15:35:05 +00:00
|
|
|
#[test]
|
2019-04-03 23:01:20 +00:00
|
|
|
fn test_crud() {
|
2020-01-12 15:31:51 +00:00
|
|
|
let conn = establish_unpooled_connection();
|
2019-04-03 23:01:20 +00:00
|
|
|
|
|
|
|
let categories = Category::list_all(&conn).unwrap();
|
|
|
|
let expected_first_category = Category {
|
|
|
|
id: 1,
|
2019-09-07 15:35:05 +00:00
|
|
|
name: "Discussion".into(),
|
2019-04-03 23:01:20 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
assert_eq!(expected_first_category, categories[0]);
|
|
|
|
}
|
|
|
|
}
|