JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Add repository settings

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨f8eaf38

⁨giterated-daemon/src/backend/settings.rs⁩ - ⁨3106⁩ bytes
Raw
1 use anyhow::Error;
2 use futures_util::StreamExt;
3 use giterated_models::model::{repository::Repository, user::User};
4 use serde_json::Value;
5 use sqlx::{Either, PgPool};
6
7 use super::SettingsBackend;
8
9 pub struct DatabaseSettings {
10 pub pg_pool: PgPool,
11 }
12
13 #[async_trait::async_trait]
14 impl SettingsBackend for DatabaseSettings {
15 async fn user_get(&mut self, user: &User) -> Result<Vec<(String, Value)>, Error> {
16 let settings = sqlx::query_as!(
17 UserSettingRow,
18 r#"SELECT * FROM user_settings WHERE username = $1"#,
19 user.username
20 )
21 .fetch_many(&self.pg_pool)
22 .filter_map(|result| async move {
23 if let Ok(Either::Right(row)) = result {
24 Some(row)
25 } else {
26 None
27 }
28 })
29 .filter_map(|row| async move {
30 if let Ok(value) = serde_json::from_str(&row.value) {
31 Some((row.name, value))
32 } else {
33 None
34 }
35 })
36 .collect::<Vec<_>>()
37 .await;
38
39 Ok(settings)
40 }
41 async fn user_write(
42 &mut self,
43 user: &User,
44 settings: &[(String, String)],
45 ) -> Result<(), Error> {
46 for (name, value) in settings {
47 sqlx::query!("INSERT INTO user_settings VALUES ($1, $2, $3) ON CONFLICT (username, name) DO UPDATE SET value = $3",
48 user.username, name, value)
49 .execute(&self.pg_pool).await?;
50 }
51
52 Ok(())
53 }
54
55 async fn repository_get(
56 &mut self,
57 repository: &Repository,
58 ) -> Result<Vec<(String, Value)>, Error> {
59 let settings = sqlx::query_as!(
60 RepositorySettingRow,
61 r#"SELECT * FROM repository_settings WHERE repository = $1"#,
62 repository.to_string()
63 )
64 .fetch_many(&self.pg_pool)
65 .filter_map(|result| async move {
66 if let Ok(Either::Right(row)) = result {
67 Some(row)
68 } else {
69 None
70 }
71 })
72 .filter_map(|row| async move {
73 if let Ok(value) = serde_json::from_str(&row.value) {
74 Some((row.name, value))
75 } else {
76 None
77 }
78 })
79 .collect::<Vec<_>>()
80 .await;
81
82 Ok(settings)
83 }
84 async fn repository_write(
85 &mut self,
86 repository: &Repository,
87 settings: &[(String, String)],
88 ) -> Result<(), Error> {
89 for (name, value) in settings {
90 sqlx::query!("INSERT INTO repository_settings VALUES ($1, $2, $3) ON CONFLICT (repository, name) DO UPDATE SET value = $3",
91 repository.to_string(), name, value)
92 .execute(&self.pg_pool).await?;
93 }
94
95 Ok(())
96 }
97 }
98
99 #[allow(unused)]
100 #[derive(Debug, sqlx::FromRow)]
101 struct UserSettingRow {
102 pub username: String,
103 pub name: String,
104 pub value: String,
105 }
106
107 #[allow(unused)]
108 #[derive(Debug, sqlx::FromRow)]
109 struct RepositorySettingRow {
110 pub repository: String,
111 pub name: String,
112 pub value: String,
113 }
114