fedimovies/src/models/notifications/types.rs

89 lines
2.4 KiB
Rust
Raw Normal View History

2021-10-12 16:11:47 +00:00
use std::convert::TryFrom;
use chrono::{DateTime, Utc};
use postgres_types::FromSql;
use tokio_postgres::Row;
use uuid::Uuid;
use crate::errors::{ConversionError, DatabaseError};
2021-10-15 00:27:39 +00:00
use crate::models::attachments::types::DbMediaAttachment;
use crate::models::posts::types::{DbPost, Post};
2021-10-12 16:11:47 +00:00
use crate::models::profiles::types::DbActorProfile;
#[allow(dead_code)]
#[derive(FromSql)]
#[postgres(name = "notification")]
struct DbNotification {
id: i32,
sender_id: Uuid,
recipient_id: Uuid,
post_id: Option<Uuid>,
event_type: i16,
created_at: DateTime<Utc>,
}
pub enum EventType {
Follow,
2021-10-15 00:27:39 +00:00
FollowRequest,
Reply,
2021-10-12 16:11:47 +00:00
}
impl From<EventType> for i16 {
fn from(value: EventType) -> i16 {
match value {
EventType::Follow => 1,
2021-10-15 00:27:39 +00:00
EventType::FollowRequest => 2,
EventType::Reply => 3,
2021-10-12 16:11:47 +00:00
}
}
}
impl TryFrom<i16> for EventType {
type Error = ConversionError;
fn try_from(value: i16) -> Result<Self, Self::Error> {
let event_type = match value {
1 => Self::Follow,
2021-10-15 00:27:39 +00:00
2 => Self::FollowRequest,
3 => Self::Reply,
2021-10-12 16:11:47 +00:00
_ => return Err(ConversionError),
};
Ok(event_type)
}
}
pub struct Notification {
pub id: i32,
pub sender: DbActorProfile,
2021-10-15 00:27:39 +00:00
pub post: Option<Post>,
2021-10-12 16:11:47 +00:00
pub event_type: EventType,
pub created_at: DateTime<Utc>,
}
impl TryFrom<&Row> for Notification {
type Error = DatabaseError;
fn try_from(row: &Row) -> Result<Self, Self::Error> {
let db_notification: DbNotification = row.try_get("notification")?;
let db_sender: DbActorProfile = row.try_get("sender")?;
2021-10-15 00:27:39 +00:00
let maybe_db_post: Option<DbPost> = row.try_get("post")?;
let maybe_post = match maybe_db_post {
Some(db_post) => {
let db_post_author: DbActorProfile = row.try_get("post_author")?;
let db_attachments: Vec<DbMediaAttachment> = row.try_get("attachments")?;
Some(Post::new(db_post, db_post_author, db_attachments))
},
None => None,
};
2021-10-12 16:11:47 +00:00
let notification = Self {
id: db_notification.id,
sender: db_sender,
2021-10-15 00:27:39 +00:00
post: maybe_post,
2021-10-12 16:11:47 +00:00
event_type: EventType::try_from(db_notification.event_type)?,
created_at: db_notification.created_at,
};
Ok(notification)
}
}