- add: initial database and auth services

This commit is contained in:
2024-11-25 20:45:16 -05:00
parent 6a35b5b373
commit 3ff22c9a5b
24 changed files with 817 additions and 1 deletions

View File

@@ -0,0 +1,123 @@
use sqlx::Error;
use sqlx::PgPool;
use serde::{Serialize, Deserialize};
use std::sync::Arc;
use crate::redis_cache::RedisCache;
use tracing::{debug, error};
#[derive(Debug, Serialize, Deserialize)]
pub struct User {
pub id: i32,
pub username: String,
pub email: String,
pub hashed_password: String,
}
pub struct UsersService {
pub pool: PgPool,
pub cache: Arc<RedisCache>, // Shared Redis cache
}
impl UsersService {
pub async fn create_user(
&self,
username: &str,
email: &str,
hashed_password: &str,
) -> Result<i32, Error> {
let result = sqlx::query!(
r#"
INSERT INTO users (username, email, hashed_password)
VALUES ($1, $2, $3)
RETURNING id
"#,
username,
email,
hashed_password
)
.fetch_one(&self.pool)
.await?;
Ok(result.id)
}
pub async fn get_user_by_id(&self, user_id: i32) -> Result<User, sqlx::Error> {
// Check Redis cache first
if let Ok(Some(cached_user)) = self.cache.get::<User>(&format!("user:{}", user_id)).await {
return Ok(cached_user);
}
// Fetch from PostgreSQL
let user = sqlx::query_as!(
User,
"SELECT id, username, email, hashed_password FROM users WHERE id = $1",
user_id
)
.fetch_one(&self.pool)
.await?;
// Store result in Redis
self.cache
.set(&format!("user:{}", user_id), &user, 3600)
.await
.unwrap_or_else(|err| eprintln!("Failed to cache user: {:?}", err));
Ok(user)
}
pub async fn get_user_by_username(&self, username: &str) -> Result<User, Error> {
// Check Redis cache first
if let Ok(Some(cached_user)) = self.cache.get::<User>(&format!("user_by_username:{}", username)).await {
return Ok(cached_user);
}
// Fetch from PostgreSQL
let user = sqlx::query_as!(
User,
"SELECT id, username, email, hashed_password FROM users WHERE username = $1",
username
)
.fetch_one(&self.pool)
.await?;
// Store result in Redis
self.cache
.set(&format!("user_by_username:{}", username), &user, 3600)
.await
.unwrap_or_else(|err| eprintln!("Failed to cache user: {:?}", err));
Ok(user)
}
pub async fn update_user_email(&self, user_id: i32, new_email: &str) -> Result<(), Error> {
sqlx::query!(
r#"
UPDATE users
SET email = $1, updated_at = CURRENT_TIMESTAMP
WHERE id = $2
"#,
new_email,
user_id
)
.execute(&self.pool)
.await?;
Ok(())
}
pub async fn delete_user(&self, user_id: i32) -> Result<(), Error> {
sqlx::query!(
r#"
DELETE FROM users
WHERE id = $1
"#,
user_id
)
.execute(&self.pool)
.await?;
Ok(())
}
}