Plume/src/models/likes.rs

52 lines
1.3 KiB
Rust
Raw Normal View History

2018-05-10 15:54:35 +00:00
use chrono;
2018-05-10 16:07:23 +00:00
use diesel::{self, PgConnection, QueryDsl, RunQueryDsl, ExpressionMethods};
2018-05-10 15:54:35 +00:00
2018-05-12 20:56:57 +00:00
use models::posts::Post;
use models::users::User;
2018-05-10 15:54:35 +00:00
use schema::likes;
2018-05-12 20:56:57 +00:00
#[derive(Queryable, Identifiable)]
2018-05-10 15:54:35 +00:00
pub struct Like {
2018-05-10 16:07:23 +00:00
pub id: i32,
pub user_id: i32,
pub post_id: i32,
pub creation_date: chrono::NaiveDateTime
2018-05-10 15:54:35 +00:00
}
#[derive(Insertable)]
#[table_name = "likes"]
pub struct NewLike {
2018-05-10 16:07:23 +00:00
pub user_id: i32,
pub post_id: i32
2018-05-10 15:54:35 +00:00
}
impl Like {
2018-05-10 16:07:23 +00:00
pub fn insert(conn: &PgConnection, new: NewLike) -> Like {
diesel::insert_into(likes::table)
.values(new)
.get_result(conn)
.expect("Unable to insert new like")
}
2018-05-10 15:54:35 +00:00
pub fn get(conn: &PgConnection, id: i32) -> Option<Like> {
likes::table.filter(likes::id.eq(id))
.limit(1)
.load::<Like>(conn)
.expect("Error loading like by ID")
.into_iter().nth(0)
}
2018-05-12 20:56:57 +00:00
pub fn for_user_on_post(conn: &PgConnection, user: &User, post: &Post) -> Option<Like> {
likes::table.filter(likes::post_id.eq(post.id))
.filter(likes::user_id.eq(user.id))
.limit(1)
.load::<Like>(conn)
.expect("Error loading like for user and post")
.into_iter().nth(0)
}
pub fn delete(&self, conn: &PgConnection) {
diesel::delete(self).execute(conn).unwrap();
}
2018-05-10 15:54:35 +00:00
}