use oiseau::cache::Cache;
use crate::model::{
Error, Result,
auth::{User, ProfileView},
};
use crate::{auto_method, DataManager};
use oiseau::{execute, get, params, query_row, PostgresRow};
impl DataManager {
pub(crate) fn get_profile_view_from_row(x: &PostgresRow) -> ProfileView {
ProfileView {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
profile: get!(x->3(i64)) as usize,
}
}
auto_method!(get_profile_view_by_id()@get_profile_view_from_row -> "SELECT * FROM profile_views WHERE id = $1" --name="profile_view" --returns=ProfileView --cache-key-tmpl="atto.profile_view:{}");
pub async fn get_profile_view_by_owner_profile(
&self,
owner: usize,
profile: usize,
) -> Result<ProfileView> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_row!(
&conn,
"SELECT * FROM profile_views WHERE owner = $1 AND profile = $2 LIMIT 1",
&[&(owner as i64), &(profile as i64)],
|x| { Ok(Self::get_profile_view_from_row(x)) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("profile view".to_string()));
}
Ok(res.unwrap())
}
pub async fn create_profile_view(&self, data: ProfileView) -> Result<usize> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO profile_views VALUES ($1, $2, $3, $4)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&(data.profile as i64),
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.incr_profile_views(data.profile).await?;
Ok(data.id)
}
pub async fn delete_profile_view(&self, id: usize, user: &User) -> Result<()> {
let y = self.get_profile_view_by_id(id).await?;
if user.id != y.owner {
return Err(Error::NotAllowed);
}
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"DELETE FROM profile_views WHERE id = $1",
&[&(id as i64)]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("atto.profile_view:{}", id)).await;
self.decr_profile_views(y.profile).await?;
Ok(())
}
}