- update: database client to implement a database trait so we can mock it out
- update unit tests - add: database client mock
This commit is contained in:
@@ -1,18 +1,28 @@
|
||||
use std::error::Error;
|
||||
use tonic::transport::Channel;
|
||||
use crate::database::{database_service_client::DatabaseServiceClient, GetUserByUsernameRequest, GetUserRequest, GetUserResponse};
|
||||
use crate::database::{database_service_client::DatabaseServiceClient, CreateUserRequest, CreateUserResponse, GetUserByUsernameRequest, GetUserRequest, GetUserResponse};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
pub trait DatabaseClientTrait: Sized {
|
||||
async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>>;
|
||||
async fn get_user_by_userid(&mut self, user_id: i32) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
|
||||
async fn get_user_by_username(&mut self, user_id: &str) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
|
||||
async fn create_user(&mut self, username: &str, email: &str, password: &str) -> Result<CreateUserResponse, Box<dyn std::error::Error>>;
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct DatabaseClient {
|
||||
client: DatabaseServiceClient<Channel>,
|
||||
}
|
||||
|
||||
impl DatabaseClient {
|
||||
pub async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
#[async_trait]
|
||||
impl DatabaseClientTrait for DatabaseClient {
|
||||
async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let client = DatabaseServiceClient::connect(endpoint.to_string()).await?;
|
||||
Ok(Self { client })
|
||||
}
|
||||
|
||||
pub async fn get_user_by_userid(
|
||||
async fn get_user_by_userid(
|
||||
&mut self,
|
||||
user_id: i32,
|
||||
) -> Result<GetUserResponse, Box<dyn std::error::Error>> {
|
||||
@@ -23,7 +33,7 @@ impl DatabaseClient {
|
||||
Ok(response.into_inner())
|
||||
}
|
||||
|
||||
pub async fn get_user_by_username(
|
||||
async fn get_user_by_username(
|
||||
&mut self,
|
||||
username: &str,
|
||||
) -> Result<GetUserResponse, Box<dyn std::error::Error>> {
|
||||
@@ -33,4 +43,14 @@ impl DatabaseClient {
|
||||
let response = self.client.get_user_by_username(request).await?;
|
||||
Ok(response.into_inner())
|
||||
}
|
||||
|
||||
async fn create_user(&mut self, username: &str, email: &str, password: &str) -> Result<CreateUserResponse, Box<dyn Error>> {
|
||||
let request = tonic::Request::new(CreateUserRequest {
|
||||
username: username.to_string(),
|
||||
email: email.to_string(),
|
||||
hashed_password: password.to_string(),
|
||||
});
|
||||
let response = self.client.create_user(request).await?;
|
||||
Ok(response.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user