-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonolithic_trait.rs
More file actions
104 lines (85 loc) · 2.33 KB
/
monolithic_trait.rs
File metadata and controls
104 lines (85 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use aws_sdk_s3::Client;
use image::RgbImage;
use rig::agent::Agent;
use rig::providers::openai;
use sqlx::PgPool;
use crate::contexts::app::App;
use crate::contexts::smart::SmartApp;
use crate::types::{User, UserId};
pub trait AppFields {
fn database(&self) -> &PgPool;
fn storage_client(&self) -> &Client;
fn bucket_id(&self) -> &str;
}
pub trait SmartAppFields: AppFields {
fn open_ai_agent(&self) -> &Agent<openai::CompletionModel>;
fn open_ai_client(&self) -> &openai::Client;
}
pub async fn get_user<Context: AppFields>(
context: &Context,
user_id: &UserId,
) -> anyhow::Result<User> {
let user =
sqlx::query_as("SELECT name, email, profile_picture_object_id FROM users WHERE id = $1")
.bind(user_id.0 as i64)
.fetch_one(context.database())
.await?;
Ok(user)
}
pub async fn fetch_storage_object<Context: AppFields>(
context: &Context,
object_id: &str,
) -> anyhow::Result<Vec<u8>> {
let output = context
.storage_client()
.get_object()
.bucket(context.bucket_id())
.key(object_id)
.send()
.await?;
let data = output.body.collect().await?.into_bytes().to_vec();
Ok(data)
}
pub async fn get_user_profile_picture<Context: AppFields>(
context: &Context,
user_id: &UserId,
) -> anyhow::Result<Option<RgbImage>> {
let user = get_user(context, user_id).await?;
if let Some(object_id) = user.profile_picture_object_id {
let data = fetch_storage_object(context, &object_id).await?;
let image = image::load_from_memory(&data)?.to_rgb8();
Ok(Some(image))
} else {
Ok(None)
}
}
impl AppFields for App {
fn database(&self) -> &PgPool {
&self.database
}
fn storage_client(&self) -> &Client {
&self.storage_client
}
fn bucket_id(&self) -> &str {
&self.bucket_id
}
}
impl AppFields for SmartApp {
fn database(&self) -> &PgPool {
&self.database
}
fn storage_client(&self) -> &Client {
&self.storage_client
}
fn bucket_id(&self) -> &str {
&self.bucket_id
}
}
impl SmartAppFields for SmartApp {
fn open_ai_agent(&self) -> &Agent<openai::CompletionModel> {
&self.open_ai_agent
}
fn open_ai_client(&self) -> &openai::Client {
&self.open_ai_client
}
}