]> Untitled Git - lemmy.git/blob - lemmy_db/src/category.rs
Isomorphic docker (#1124)
[lemmy.git] / lemmy_db / src / category.rs
1 use crate::{
2   schema::{category, category::dsl::*},
3   Crud,
4 };
5 use diesel::{dsl::*, result::Error, *};
6 use serde::Serialize;
7
8 #[derive(Queryable, Identifiable, PartialEq, Debug, Serialize)]
9 #[table_name = "category"]
10 pub struct Category {
11   pub id: i32,
12   pub name: String,
13 }
14
15 #[derive(Insertable, AsChangeset)]
16 #[table_name = "category"]
17 pub struct CategoryForm {
18   pub name: String,
19 }
20
21 impl Crud<CategoryForm> for Category {
22   fn read(conn: &PgConnection, category_id: i32) -> Result<Self, Error> {
23     category.find(category_id).first::<Self>(conn)
24   }
25
26   fn create(conn: &PgConnection, new_category: &CategoryForm) -> Result<Self, Error> {
27     insert_into(category)
28       .values(new_category)
29       .get_result::<Self>(conn)
30   }
31
32   fn update(
33     conn: &PgConnection,
34     category_id: i32,
35     new_category: &CategoryForm,
36   ) -> Result<Self, Error> {
37     diesel::update(category.find(category_id))
38       .set(new_category)
39       .get_result::<Self>(conn)
40   }
41 }
42
43 impl Category {
44   pub fn list_all(conn: &PgConnection) -> Result<Vec<Self>, Error> {
45     category.load::<Self>(conn)
46   }
47 }
48
49 #[cfg(test)]
50 mod tests {
51   use crate::{category::Category, tests::establish_unpooled_connection};
52
53   #[test]
54   fn test_crud() {
55     let conn = establish_unpooled_connection();
56
57     let categories = Category::list_all(&conn).unwrap();
58     let expected_first_category = Category {
59       id: 1,
60       name: "Discussion".into(),
61     };
62
63     assert_eq!(expected_first_category, categories[0]);
64   }
65 }