Skip to content

Commit

Permalink
pool生成関数を切り出す
Browse files Browse the repository at this point in the history
テストのときとかに使いまわしやすくなった
  • Loading branch information
puripuri2100 committed Aug 11, 2023
1 parent 3194e53 commit 306d284
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 9 deletions.
7 changes: 2 additions & 5 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use anyhow::{Context, Result};
use anyhow::Result;
use axum::{
routing::{get, post},
Router,
};
use sqlx::postgres::PgPool;
use std::net::SocketAddr;
use std::sync::Arc;

Expand All @@ -13,11 +12,9 @@ pub mod equipment;
/// サーバーの実体
/// データベースを起動してエントリポイントに応じて関数を呼び出す
pub async fn app(bind: SocketAddr) -> Result<()> {
let database_url =
std::env::var("DATABASE_URL").context("Environment variable not set: DATABASE_URL")?;
let conn = Arc::new(crate::database::create_pool().await?);

// migrateファイルを適用
let conn = Arc::new(PgPool::connect(&database_url).await?);
crate::database::migrate(&mut conn.acquire().await?).await?;

// pathと関数の実体の紐づけ
Expand Down
5 changes: 1 addition & 4 deletions src/app/equipment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,13 @@ pub async fn insert_equipment(
mod tests {
use axum::{extract::Json, http::StatusCode};
use serde_json::json;
use sqlx::postgres::PgPool;
use std::sync::Arc;

use crate::app::equipment::insert_equipment;

#[tokio::test]
async fn test_insert_equipment() {
let database_url = std::env::var("DATABASE_URL").unwrap();

let conn = Arc::new(PgPool::connect(&database_url).await.unwrap());
let conn = Arc::new(crate::database::create_pool().await.unwrap());

let status_code = insert_equipment(
Json(
Expand Down
10 changes: 10 additions & 0 deletions src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
//!

use anyhow::{Context, Result};
use sqlx::{pool::Pool, postgres::PgPool, Postgres};

/// 物品登録を行う関数を提供する
pub mod insert_equipment;
Expand All @@ -26,3 +27,12 @@ where
.await
.context("Failed to run migrations")
}

/// poolを生成する
pub async fn create_pool() -> Result<Pool<Postgres>> {
let database_url =
std::env::var("DATABASE_URL").context("Environment variable not set: DATABASE_URL")?;
let conn = PgPool::connect(&database_url).await?;

Ok(conn)
}

0 comments on commit 306d284

Please sign in to comment.