-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcgp_impl.rs
More file actions
106 lines (90 loc) · 2.63 KB
/
cgp_impl.rs
File metadata and controls
106 lines (90 loc) · 2.63 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
105
106
use aws_sdk_s3::Client;
use cgp::prelude::*;
use google_cloud_storage::client::Storage;
use image::RgbImage;
use sqlx::PgPool;
use crate::contexts::app::App;
use crate::contexts::gcloud::GCloudApp;
use crate::types::{User, UserId};
#[cgp_fn]
#[async_trait]
pub async fn get_user(
&self,
#[implicit] database: &PgPool,
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(database)
.await?;
Ok(user)
}
#[async_trait]
#[cgp_component(StorageObjectFetcher)]
pub trait CanFetchStorageObject {
async fn fetch_storage_object(&self, object_id: &str) -> anyhow::Result<Vec<u8>>;
}
#[cgp_impl(new FetchS3Object)]
impl StorageObjectFetcher {
async fn fetch_storage_object(
&self,
#[implicit] storage_client: &Client,
#[implicit] bucket_id: &str,
object_id: &str,
) -> anyhow::Result<Vec<u8>> {
let output = storage_client
.get_object()
.bucket(bucket_id)
.key(object_id)
.send()
.await?;
let data = output.body.collect().await?.into_bytes().to_vec();
Ok(data)
}
}
#[cgp_impl(new FetchGCloudObject)]
impl StorageObjectFetcher {
async fn fetch_storage_object(
&self,
#[implicit] storage_client: &Storage,
#[implicit] bucket_id: &str,
object_id: &str,
) -> anyhow::Result<Vec<u8>> {
let mut reader = storage_client
.read_object(bucket_id, object_id)
.send()
.await?;
let mut contents = Vec::new();
while let Some(chunk) = reader.next().await.transpose()? {
contents.extend_from_slice(&chunk);
}
Ok(contents)
}
}
#[cgp_fn]
#[async_trait]
#[uses(GetUser, CanFetchStorageObject)]
pub async fn get_user_profile_picture(&self, user_id: &UserId) -> anyhow::Result<Option<RgbImage>> {
let user = self.get_user(user_id).await?;
if let Some(object_id) = user.profile_picture_object_id {
let data = self.fetch_storage_object(&object_id).await?;
let image = image::load_from_memory(&data)?.to_rgb8();
Ok(Some(image))
} else {
Ok(None)
}
}
delegate_components! {
App {
StorageObjectFetcherComponent: FetchS3Object,
}
}
delegate_components! {
GCloudApp {
StorageObjectFetcherComponent: FetchGCloudObject,
}
}
pub trait CheckGetUserProfilePicture: GetUserProfilePicture {}
impl CheckGetUserProfilePicture for App {}
impl CheckGetUserProfilePicture for GCloudApp {}