-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsync.rs
More file actions
152 lines (125 loc) · 3.92 KB
/
sync.rs
File metadata and controls
152 lines (125 loc) · 3.92 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use serde::{Deserialize, Serialize};
use thiserror::Error;
// ============ Error Handling ============
#[derive(Error, Debug)]
pub enum AppError {
#[error("Repository not found: {0}")]
NotFound(String),
#[error("Validation failed: {0}")]
Validation(String),
#[error("Internal error: {0}")]
Internal(#[from] std::io::Error),
#[error("Serialization error: {0}")]
Serialization(#[from] serde_json::Error),
}
type Result<T> = std::result::Result<T, AppError>;
// ============ Domain Models ============
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: String,
pub name: String,
pub email: String,
pub role: Role,
pub tags: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Role {
Admin,
Editor,
Viewer,
}
impl User {
pub fn new(name: impl Into<String>, email: impl Into<String>, role: Role) -> Self {
Self {
id: uuid::Uuid::new_v4().to_string(),
name: name.into(),
email: email.into(),
role,
tags: Vec::new(),
}
}
pub fn is_admin(&self) -> bool {
self.role == Role::Admin
}
}
// ============ Repository Trait ============
#[async_trait::async_trait]
pub trait Repository: Send + Sync {
async fn find_all(&self) -> Result<Vec<User>>;
async fn find_by_id(&self, id: &str) -> Result<Option<User>>;
async fn create(&self, user: User) -> Result<User>;
async fn update(&self, id: &str, user: User) -> Result<User>;
async fn delete(&self, id: &str) -> Result<bool>;
}
// ============ In-Memory Implementation ============
pub struct InMemoryRepo {
store: Arc<RwLock<HashMap<String, User>>>,
}
impl InMemoryRepo {
pub fn new() -> Self {
Self {
store: Arc::new(RwLock::new(HashMap::new())),
}
}
}
#[async_trait::async_trait]
impl Repository for InMemoryRepo {
async fn find_all(&self) -> Result<Vec<User>> {
let store = self.store.read().await;
Ok(store.values().cloned().collect())
}
async fn find_by_id(&self, id: &str) -> Result<Option<User>> {
let store = self.store.read().await;
Ok(store.get(id).cloned())
}
async fn create(&self, user: User) -> Result<User> {
let mut store = self.store.write().await;
store.insert(user.id.clone(), user.clone());
Ok(user)
}
async fn update(&self, id: &str, user: User) -> Result<User> {
let mut store = self.store.write().await;
if !store.contains_key(id) {
return Err(AppError::NotFound(id.to_string()));
}
store.insert(id.to_string(), user.clone());
Ok(user)
}
async fn delete(&self, id: &str) -> Result<bool> {
let mut store = self.store.write().await;
Ok(store.remove(id).is_some())
}
}
// ============ Service Layer ============
pub struct UserService<R: Repository> {
repo: R,
}
impl<R: Repository> UserService<R> {
pub fn new(repo: R) -> Self {
Self { repo }
}
pub async fn get_admins(&self) -> Result<Vec<User>> {
let users = self.repo.find_all().await?;
Ok(users.into_iter().filter(|u| u.is_admin()).collect())
}
pub async fn create_user(&self, name: &str, email: &str, role: Role) -> Result<User> {
if name.is_empty() {
return Err(AppError::Validation("Name cannot be empty".into()));
}
let user = User::new(name, email, role);
self.repo.create(user).await
}
}
#[tokio::main]
async fn main() -> Result<()> {
let repo = InMemoryRepo::new();
let service = UserService::new(repo);
let admin = service.create_user("Alice", "alice@example.com", Role::Admin).await?;
println!("Created: {} ({})", admin.name, admin.id);
let admins = service.get_admins().await?;
println!("Total admins: {}", admins.len());
Ok(())
}