Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

特定ユーザ取得APIの実装 #70

Merged
merged 14 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ sea-orm = { version = "0.12", features = [
"sqlx-postgres",
"runtime-tokio-native-tls",
"macros",
"mock",
] }
2 changes: 2 additions & 0 deletions backend/db-schema/migrations/20240908082102_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "User" ALTER COLUMN "updated_at" DROP NOT NULL;
2 changes: 1 addition & 1 deletion backend/db-schema/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ model User {
user_name String @unique
display_name String @db.VarChar(255)
created_at DateTime @default(now())
updated_at DateTime @updatedAt
updated_at DateTime? @updatedAt
channel Channel[]
message Message[]
channel_user ChannelUser[]
Expand Down
2 changes: 1 addition & 1 deletion backend/src/generate/entities/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub struct Model {
pub user_name: String,
pub display_name: String,
pub created_at: DateTime,
pub updated_at: DateTime,
pub updated_at: Option<DateTime>,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
Expand Down
1 change: 1 addition & 0 deletions backend/src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod mutation;
pub mod query;
mod test_handler;
mod user;
4 changes: 3 additions & 1 deletion backend/src/handler/query.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::handler::test_handler::TestQuery;
use async_graphql::MergedObject;

use crate::handler::user::UserQuery;

#[derive(MergedObject, Default)]
pub struct Query(TestQuery);
pub struct Query(TestQuery, UserQuery);
27 changes: 27 additions & 0 deletions backend/src/handler/user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use async_graphql::Error;
use async_graphql::Object;
use async_graphql::Result;

use crate::context::Context;
use crate::models;
use crate::usecase;

#[derive(Default)]
pub struct UserQuery;

#[Object]
impl UserQuery {
async fn user<'ctx>(
&self,
ctx: &async_graphql::Context<'ctx>,
id: String,
) -> Result<models::user::User> {
let ctx = ctx.data_unchecked::<Context>();

match usecase::user::get_user_by_id(ctx, id.as_str()).await {
Ok(Some(user)) => Ok(user),
Ok(None) => Err(Error::new("Not found")),
Err(_) => Err(Error::new("Internal server error")),
}
}
}
1 change: 1 addition & 0 deletions backend/src/models.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod test;
pub mod user;
8 changes: 8 additions & 0 deletions backend/src/models/user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use async_graphql::SimpleObject;

#[derive(SimpleObject, Debug, Eq, PartialEq)]
pub struct User {
pub id: String,
pub name: String,
pub display_name: String,
}
1 change: 1 addition & 0 deletions backend/src/usecase.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod test;
pub mod user;
86 changes: 86 additions & 0 deletions backend/src/usecase/user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
use sea_orm::EntityTrait;

use crate::generate::entities::user;
use crate::{context::Context, models::user::User};

pub async fn get_user_by_id(ctx: &Context, id: &str) -> Result<Option<User>, ()> {
let db = &ctx.db;

let Ok(user) = user::Entity::find_by_id(id).one(db).await else {
return Err(());
};

Ok(user.map(|user| User {
id: user.id,
name: user.user_name,
display_name: user.display_name,
}))
}

#[cfg(test)]
pub mod test {
use sea_orm::prelude::*;
use sea_orm::DatabaseConnection;
use sea_orm::MockDatabase;

use crate::context::Context;
use crate::generate::entities::user;
use crate::models::user::User;
use crate::usecase::user::get_user_by_id;

#[tokio::test]
async fn 指定IDのユーザが取得される() {
// Arrange
let id = "4e36eb58-49a5-43aa-935f-5a5cccb77a90";

let db: DatabaseConnection = MockDatabase::new(sea_orm::DatabaseBackend::Postgres)
.append_query_results([vec![user::Model {
id: id.to_string(),
user_name: "aiueo".to_string(),
display_name: "あいうえお".to_string(),
created_at: DateTime::parse_from_str("2024-08-08 00:00:00", "%Y-%m-%d %H:%M:%S")
.unwrap(),
updated_at: None,
}]])
.into_connection();

let ctx = Context {
env: "".to_string(),
db,
};

// Action
let result = get_user_by_id(&ctx, id).await;

// Assert
assert_eq!(
result,
Ok(Some(User {
id: id.to_string(),
name: "aiueo".to_string(),
display_name: "あいうえお".to_string(),
}))
);
}

#[tokio::test]
async fn 指定IDのユーザが存在しない場合None() {
// Arrange
let id = "4e36eb58-49a5-43aa-935f-5a5cccb77a90";

let db: DatabaseConnection = MockDatabase::new(sea_orm::DatabaseBackend::Postgres)
.append_query_results(vec![Vec::<user::Model>::new()])
.into_connection();

let ctx = Context {
env: "".to_string(),
db,
};

// Action
let result = get_user_by_id(&ctx, "存在しないID").await;

// Assert
assert_eq!(result, Ok(None));
}
}