Skip to content

Commit

Permalink
ファイル分割の見直し / 関数からimplへの移行
Browse files Browse the repository at this point in the history
  • Loading branch information
Pugma committed Jul 10, 2024
1 parent 402a006 commit 00691f5
Show file tree
Hide file tree
Showing 7 changed files with 211 additions and 181 deletions.
9 changes: 9 additions & 0 deletions server/app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,12 @@ once_cell = "1.19.0"
uuid = { version = "1.8.0", features = ["v7"] }
tower-http = {version = "0.5.2", features = ["fs"]}
bcrypt = "0.15.1"
async-session = "3.0.0"
anyhow = "1.0.86"
serde = "1.0.204"

[dependencies.async-sqlx-session]
git = "https://github.com/maxcountryman/async-sqlx-session.git"
default-features = false
branch = "sqlx-0.7"
features = ["mysql"]
138 changes: 0 additions & 138 deletions server/app/src/db.rs

This file was deleted.

27 changes: 8 additions & 19 deletions server/app/src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use axum_extra::extract::CookieJar;
use core::{future::Future, marker, pin};
use sqlx::{mysql::MySqlQueryResult, MySql, Pool};
use sqlx::mysql::MySqlQueryResult;

use crate::db::{self};
use crate::repository::Repository;
use axum::async_trait;
use openapi::{
models::{
Expand All @@ -13,17 +13,8 @@ use openapi::{
ScheduleGroupIdPutResponse, SignUpPostResponse,
};

#[derive(Clone)]
pub struct Count(pub Pool<MySql>);

impl AsRef<Count> for Count {
fn as_ref(&self) -> &Count {
self
}
}

#[async_trait]
impl Api for Count {
impl Api for Repository {
fn sign_up_post<'life0, 'async_trait>(
&'life0 self,
_method: axum::http::Method,
Expand All @@ -38,9 +29,8 @@ impl Api for Count {
Self: 'async_trait,
{
let db_result: Result<MySqlQueryResult, String> = tokio::task::block_in_place(move || {
tokio::runtime::Handle::current().block_on(async move {
db::add_user(self.0.clone(), body.user_name, body.password).await
})
tokio::runtime::Handle::current()
.block_on(async move { self.add_user(body.user_name, body.password).await })
});

let result = match db_result {
Expand Down Expand Up @@ -70,9 +60,8 @@ impl Api for Count {
{
let copied_password: String = body.password.clone();
let db_result: Result<bool, String> = tokio::task::block_in_place(move || {
tokio::runtime::Handle::current().block_on(async move {
db::check_user(self.0.clone(), body.user_name, body.password).await
})
tokio::runtime::Handle::current()
.block_on(async move { self.check_user(body.user_name, body.password).await })
});

let result = match db_result {
Expand Down Expand Up @@ -106,7 +95,7 @@ impl Api for Count {

let db_result: Result<Vec<GroupItem>, String> = tokio::task::block_in_place(move || {
tokio::runtime::Handle::current()
.block_on(async move { db::get_groups_by_user(self.0.clone(), user_name).await })
.block_on(async move { self.get_groups_by_user(user_name).await })
});

let result = match db_result {
Expand Down
38 changes: 14 additions & 24 deletions server/app/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,24 @@
pub mod db;
pub mod handler;
mod handler;
mod repository;

use anyhow::Ok;

extern crate openapi;
// use sqlx::migrate::Migrator;
// use std::{path::Path, thread};
use std::thread;
use tower_http::services::{ServeDir, ServeFile};

use db::setup_db;

use crate::handler::Count;
use repository::Repository;

#[tokio::main]
async fn main() {
let db_pool = thread::spawn(|| match setup_db() {
Ok(a) => {
println!("Correctly connected to DB!");
a
}
Err(a) => panic!("{a}"),
})
.join()
.expect("Thread panicked");

// let _m = Migrator::new(Path::new("./migrations")).await.unwrap();

let state = Count(db_pool);
async fn main() -> anyhow::Result<()> {
// DB 初期化
let state = Repository::setup_db().await?;
state.migrate().await?;

// 静的ファイル配信設定
let static_dir = ServeFile::new("/dist/index.html");
let serve_dir_from_assets = ServeDir::new("/dist/assets/");

// 最初に初期化をする
// API 初期化
let app = openapi::server::new(state)
.nest_service("/assets", serve_dir_from_assets)
.fallback_service(static_dir);
Expand All @@ -38,5 +27,6 @@ async fn main() {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();

// start listening
axum::serve(listener, app).await.unwrap();
axum::serve(listener, app).await?;
Ok(())
}
105 changes: 105 additions & 0 deletions server/app/src/repository.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
use anyhow::Ok;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};

use sqlx::mysql::{MySqlConnectOptions, MySqlPoolOptions, MySqlQueryResult};
use sqlx::{FromRow, MySqlPool};

use std::env;
use std::string::String;

const MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("../../docs");

use async_sqlx_session::MySqlSessionStore;
use openapi::models::GroupItem;

mod user_groups;
mod user_passwords;
mod user_sessions;

#[derive(Clone)]
pub struct Repository {
pool: MySqlPool,
session_store: MySqlSessionStore,
bcrypt_cost: u32,
}

impl Repository {
pub async fn setup_db() -> anyhow::Result<Self> {
// コネクションプールの設定
let pool = MySqlPoolOptions::new()
.max_connections(10)
.connect_with(CONFIG.options())
.await?;
let session_store =
MySqlSessionStore::from_client(pool.clone()).with_table_name("user_sessions");
Ok(Self {
pool,
session_store,
bcrypt_cost: bcrypt::DEFAULT_COST,
})
}

pub async fn migrate(&self) -> anyhow::Result<()> {
MIGRATOR.run(&self.pool).await?;
self.session_store.migrate().await?;
Ok(())
}
}

impl AsRef<Repository> for Repository {
fn as_ref(&self) -> &Repository {
self
}
}

pub struct DataBaseConfig {
db_hostname: String,
db_database: String,
db_username: String,
db_password: String,
db_port: u16,
}

#[derive(FromRow)]
pub struct Password(String);

impl Password {
fn to_string(&self) -> &str {
&self.0
}
}

#[derive(FromRow)]
struct DbGroupItem {
group_uuid: sqlx::types::Uuid,
group_name: String,
}

impl DbGroupItem {
fn to_group_item(&self) -> GroupItem {
GroupItem::new(self.group_uuid, self.group_name.clone())
}
}

impl DataBaseConfig {
fn options(&self) -> MySqlConnectOptions {
MySqlConnectOptions::new()
.host(&self.db_hostname)
.port(self.db_port)
.username(&self.db_username)
.password(&self.db_password)
.database(&self.db_database)
}
}

static CONFIG: Lazy<DataBaseConfig> = Lazy::new(|| DataBaseConfig {
db_hostname: env::var("DB_HOSTNAME").unwrap(),
db_port: env::var("DB_PORT").unwrap().parse().unwrap(),
db_username: env::var("DB_USERNAME").unwrap(),
db_password: env::var("DB_PASSWORD").unwrap(),
db_database: env::var("DB_DATABASE").unwrap(),
});

#[derive(FromRow, Deserialize, Serialize)]
pub struct UserName(String);
Loading

0 comments on commit 00691f5

Please sign in to comment.