initial commit
This commit is contained in:
commit
8a19a733d6
35 changed files with 2489 additions and 0 deletions
86
src/models/playlist.rs
Normal file
86
src/models/playlist.rs
Normal file
|
@ -0,0 +1,86 @@
|
|||
use crate::helpers::db;
|
||||
use crate::models::tracks::Tracks;
|
||||
use crate::models::user::Users;
|
||||
use crate::schema::playlists;
|
||||
use chrono::NaiveDateTime;
|
||||
use diesel::result::Error;
|
||||
use diesel::{
|
||||
AsChangeset, EqAll, ExpressionMethods, Insertable, QueryDsl, Queryable, RunQueryDsl, Selectable,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct PlaylistCreator {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(AsChangeset, Insertable, Queryable, Selectable, Deserialize, Serialize)]
|
||||
#[diesel(table_name = crate::schema::playlists)]
|
||||
#[diesel(belongs_to(Users))]
|
||||
#[diesel(check_for_backend(diesel::pg::Pg))]
|
||||
pub struct Playlist {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub creator_id: String,
|
||||
|
||||
pub created_at: NaiveDateTime,
|
||||
pub updated_at: Option<NaiveDateTime>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Queryable, Serialize)]
|
||||
pub struct Playlists {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub creator_id: String,
|
||||
|
||||
pub created_at: NaiveDateTime,
|
||||
pub updated_at: Option<NaiveDateTime>,
|
||||
}
|
||||
|
||||
impl Playlists {
|
||||
pub fn find(id: &str) -> Result<Self, Error> {
|
||||
let conn = &mut db::connection()?;
|
||||
let playlist = playlists::table.filter(playlists::id.eq(id)).first(conn)?;
|
||||
Ok(playlist)
|
||||
}
|
||||
|
||||
pub fn create(playlist: Playlist) -> Result<Self, Error> {
|
||||
let conn = &mut db::connection()?;
|
||||
let playlist = diesel::insert_into(playlists::table)
|
||||
.values(Playlist::from(playlist))
|
||||
.get_result(conn)?;
|
||||
Ok(playlist)
|
||||
}
|
||||
|
||||
pub fn find_for_user(user_id: &str) -> Result<Vec<Playlists>, Error> {
|
||||
let conn = &mut db::connection()?;
|
||||
let playlists = playlists::table
|
||||
.filter(playlists::creator_id.eq(user_id))
|
||||
.get_results(conn)?;
|
||||
Ok(playlists)
|
||||
}
|
||||
|
||||
pub fn get_tracks(&self) -> Result<Vec<Tracks>, Error> {
|
||||
let tracks = Tracks::find_by_playlist(&self.id)?;
|
||||
Ok(tracks)
|
||||
}
|
||||
|
||||
pub fn get_creator(&self) -> Result<Users, Error> {
|
||||
let creator = Users::find(&self.creator_id)?;
|
||||
Ok(creator)
|
||||
}
|
||||
}
|
||||
|
||||
impl Playlist {
|
||||
fn from(playlist: Playlist) -> Playlist {
|
||||
Playlist {
|
||||
id: playlist.id,
|
||||
name: playlist.name,
|
||||
creator_id: playlist.creator_id,
|
||||
|
||||
created_at: playlist.created_at,
|
||||
updated_at: playlist.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue