Add Favorite GET, and POST endpoints

This commit is contained in:
Cameron Cordes
2020-08-07 22:56:29 -04:00
parent 74043c5c6a
commit c774edd7dd
7 changed files with 86 additions and 5 deletions

View File

@@ -3,7 +3,7 @@ use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use dotenv::dotenv;
use crate::database::models::{InsertUser, User};
use crate::database::models::{Favorite, InsertFavorite, InsertUser, User};
mod models;
mod schema;
@@ -68,3 +68,25 @@ pub fn user_exists(name: &str) -> bool {
.first()
.is_some()
}
pub fn add_favorite(user_id: i32, favorite_path: String) {
use schema::favorites::dsl::*;
let connection = connect();
diesel::insert_into(favorites)
.values(InsertFavorite {
userid: &user_id,
path: &favorite_path,
})
.execute(&connection)
.unwrap();
}
pub fn get_favorites(user_id: i32) -> Vec<Favorite> {
use schema::favorites::dsl::*;
favorites
.filter(userid.eq(user_id))
.load::<Favorite>(&connect())
.unwrap_or_default()
}

View File

@@ -1,4 +1,4 @@
use crate::database::schema::users;
use crate::database::schema::{favorites, users};
use serde::Serialize;
#[derive(Insertable)]
@@ -15,3 +15,17 @@ pub struct User {
#[serde(skip_serializing)]
pub password: String,
}
#[derive(Insertable)]
#[table_name = "favorites"]
pub struct InsertFavorite<'a> {
pub userid: &'a i32,
pub path: &'a str,
}
#[derive(Serialize, Queryable, Clone, Debug)]
pub struct Favorite {
pub id: i32,
pub userid: i32,
pub path: String,
}

View File

@@ -1,3 +1,11 @@
table! {
favorites (id) {
id -> Integer,
userid -> Integer,
path -> Text,
}
}
table! {
users (id) {
id -> Integer,
@@ -5,3 +13,5 @@ table! {
password -> Text,
}
}
allow_tables_to_appear_in_same_query!(favorites, users,);