-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #44 from traP-jp/feat/user-impl
impl UserService
Showing
6 changed files
with
217 additions
and
2 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
CREATE TABLE IF NOT EXISTS `users` ( | ||
`id` BINARY(16) NOT NULL, | ||
`name` VARCHAR(255) NOT NULL, | ||
`display_name` VARCHAR(255) NOT NULL, | ||
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, | ||
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, | ||
PRIMARY KEY (`id`) | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
#[derive(Debug, thiserror::Error)] | ||
pub enum Error { | ||
#[error("Not found")] | ||
NotFound, | ||
#[error("Database error")] | ||
Sqlx(#[from] sqlx::Error), | ||
} | ||
|
||
impl From<Error> for tonic::Status { | ||
fn from(value: Error) -> Self { | ||
match value { | ||
Error::NotFound => tonic::Status::not_found("Not found"), | ||
Error::Sqlx(_) => tonic::Status::internal("Database error"), | ||
} | ||
} | ||
} | ||
|
||
pub type Result<T, E = Error> = std::result::Result<T, E>; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
use std::sync::Arc; | ||
|
||
use schema::user as schema; | ||
|
||
use crate::prelude::IntoStatus; | ||
|
||
// MARK: type conversions | ||
|
||
impl From<super::User> for schema::User { | ||
fn from(value: super::User) -> Self { | ||
let super::User { | ||
id, | ||
name, | ||
display_name, | ||
created_at, | ||
updated_at: _, | ||
} = value; | ||
Self { | ||
id: id.0.to_string(), | ||
name, | ||
display_name, | ||
created_at: Some(created_at.into()), | ||
} | ||
} | ||
} | ||
|
||
// MARK: ServiceImpl | ||
|
||
pub struct ServiceImpl<State> { | ||
state: Arc<State>, | ||
} | ||
|
||
impl<State> Clone for ServiceImpl<State> | ||
where | ||
State: super::ProvideUserService, | ||
{ | ||
fn clone(&self) -> Self { | ||
Self { | ||
state: Arc::clone(&self.state), | ||
} | ||
} | ||
} | ||
|
||
impl<State> ServiceImpl<State> | ||
where | ||
State: super::ProvideUserService, | ||
{ | ||
pub(super) fn new(state: Arc<State>) -> Self { | ||
Self { state } | ||
} | ||
} | ||
|
||
#[async_trait::async_trait] | ||
impl<State> schema::user_service_server::UserService for ServiceImpl<State> | ||
where | ||
State: super::ProvideUserService, | ||
{ | ||
async fn get_user( | ||
&self, | ||
request: tonic::Request<schema::GetUserRequest>, | ||
) -> Result<tonic::Response<schema::GetUserResponse>, tonic::Status> { | ||
let (_, _, schema::GetUserRequest { id }) = request.into_parts(); | ||
let req = super::GetUser { | ||
id: super::UserId( | ||
uuid::Uuid::parse_str(&id) | ||
.map_err(|_| tonic::Status::invalid_argument("Invalid UUID"))?, | ||
), | ||
}; | ||
let user = self | ||
.state | ||
.get_user(req) | ||
.await | ||
.map_err(IntoStatus::into_status)? | ||
.into(); | ||
let res = schema::GetUserResponse { user: Some(user) }; | ||
Ok(tonic::Response::new(res)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
use crate::prelude::Timestamp; | ||
use futures::{future::BoxFuture, FutureExt}; | ||
use serde::{Deserialize, Serialize}; | ||
use sqlx::{FromRow, MySqlPool}; | ||
use uuid::Uuid; | ||
|
||
impl<Context> super::UserService<Context> for super::UserServiceImpl | ||
where | ||
Context: AsRef<MySqlPool>, | ||
{ | ||
type Error = super::Error; | ||
|
||
fn get_user<'a>( | ||
&'a self, | ||
ctx: &'a Context, | ||
req: super::GetUser, | ||
) -> BoxFuture<'a, Result<super::User, Self::Error>> { | ||
get_user(ctx.as_ref(), req).boxed() | ||
} | ||
|
||
fn create_user<'a>( | ||
&'a self, | ||
ctx: &'a Context, | ||
req: super::CreateUser, | ||
) -> BoxFuture<'a, Result<super::User, Self::Error>> { | ||
create_user(ctx.as_ref(), req).boxed() | ||
} | ||
} | ||
|
||
// MARK: DB operations | ||
|
||
#[derive(Debug, Clone, Hash, Deserialize, Serialize, FromRow)] | ||
struct UserRow { | ||
pub id: Uuid, | ||
pub name: String, | ||
pub display_name: String, | ||
pub created_at: chrono::DateTime<chrono::Utc>, | ||
pub updated_at: chrono::DateTime<chrono::Utc>, | ||
} | ||
|
||
impl From<UserRow> for super::User { | ||
fn from(value: UserRow) -> Self { | ||
Self { | ||
id: super::UserId(value.id), | ||
name: value.name, | ||
display_name: value.display_name, | ||
updated_at: Timestamp(value.updated_at), | ||
created_at: Timestamp(value.created_at), | ||
} | ||
} | ||
} | ||
|
||
async fn get_user(pool: &MySqlPool, request: super::GetUser) -> Result<super::User, super::Error> { | ||
let super::GetUser { | ||
id: super::UserId(id), | ||
} = request; | ||
let user: Option<UserRow> = sqlx::query_as(r#"SELECT * FROM `users` WHERE `id` = ?"#) | ||
.bind(id) | ||
.fetch_optional(pool) | ||
.await?; | ||
user.map_or(Err(super::Error::NotFound), |user| Ok(user.into())) | ||
} | ||
|
||
async fn create_user( | ||
pool: &MySqlPool, | ||
request: super::CreateUser, | ||
) -> Result<super::User, super::Error> { | ||
let super::CreateUser { name, display_name } = request; | ||
let id = Uuid::now_v7(); | ||
sqlx::query( | ||
r#" | ||
INSERT INTO `users` (`id`, `name`, `display_name`) | ||
VALUES (?, ?, ?) | ||
"#, | ||
) | ||
.bind(id) | ||
.bind(name) | ||
.bind(display_name) | ||
.execute(pool) | ||
.await?; | ||
tracing::info!(id = %id, "Created a user"); | ||
let user = get_user( | ||
pool, | ||
super::GetUser { | ||
id: super::UserId(id), | ||
}, | ||
) | ||
.await?; | ||
Ok(user) | ||
} |