From 1a82808aebdd8161bb9b40395af77e24d45f25c4 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Fri, 22 Oct 2021 20:39:01 +0200 Subject: Add establishing of database connection Signed-off-by: Matthias Beyer --- service-person/Cargo.toml | 2 +- service-person/src/main.rs | 32 +++++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/service-person/Cargo.toml b/service-person/Cargo.toml index c78dfb8..7f447a2 100644 --- a/service-person/Cargo.toml +++ b/service-person/Cargo.toml @@ -9,4 +9,4 @@ env_logger = "0.8" actix-web = "3.3" anyhow = "1" serde = "1" -diesel = { version = "1.4.4", features = ["postgres"] } +diesel = { version = "1.4.4", features = ["postgres", "r2d2"] } diff --git a/service-person/src/main.rs b/service-person/src/main.rs index 759050d..1a47c51 100644 --- a/service-person/src/main.rs +++ b/service-person/src/main.rs @@ -1,12 +1,39 @@ +#[macro_use] +extern crate diesel; + use std::str::FromStr; use anyhow::Context; use actix_web::{web, App, HttpServer, HttpResponse, Result}; +use diesel::pg::PgConnection; +use diesel::prelude::*; +use diesel::r2d2::ConnectionManager; +use diesel::r2d2::Pool; mod model; use model::*; + +type DbPool = Pool>; + +pub fn establish_connection() -> DbPool { + let database_url = std::env::var("DATABASE_URL") + .expect("DATABASE_URL must be set"); + + let pool_max_size = std::env::var("DATABASE_MAX_CONNECTIONS") + .as_ref() + .map(|s| u32::from_str(s)) + .expect("DATABASE_URL must be set") + .expect("Failed to parse string into integer for DATABASE_MAX_CONNECTIONS"); + + let manager = diesel::r2d2::ConnectionManager::new(&database_url); + diesel::r2d2::Pool::builder() + .max_size(pool_max_size) + .build(manager) + .expect(&format!("Error connection to {}", database_url)) +} + async fn create_person(person: web::Json) -> Result { log::debug!("Creating person = {:?}", person); Ok(HttpResponse::Ok().finish()) @@ -23,8 +50,11 @@ async fn main() -> anyhow::Result<()> { .expect("environment: PORT variable not set") .context("Failed to parse port as integer")?; - HttpServer::new(|| { + let db_connection_pool = establish_connection(); + + HttpServer::new(move || { App::new() + .data(db_connection_pool.clone()) .route("/create", web::post().to(create_person)) }) .bind(format!("{}:{}", bind, port))? -- cgit v1.2.3