From 952f66102d4508cc055720e47c09f59aa19e1105 Mon Sep 17 00:00:00 2001 From: Jonni Liljamo Date: Fri, 17 Feb 2023 12:46:56 +0200 Subject: [PATCH] feat(api): database connection --- api/src/main.rs | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/api/src/main.rs b/api/src/main.rs index c4257b2..0aae4b2 100644 --- a/api/src/main.rs +++ b/api/src/main.rs @@ -6,7 +6,15 @@ * See LICENSE for licensing information. */ -use actix_web::{get, middleware::Logger, App, HttpResponse, HttpServer, Responder}; +use actix_web::{get, middleware::Logger, web, App, HttpResponse, HttpServer, Responder}; + +use diesel::{ + self, + r2d2::{self, ConnectionManager}, + PgConnection, +}; + +type PgPool = r2d2::Pool>; #[get("/ping")] async fn ping() -> impl Responder { @@ -20,8 +28,20 @@ async fn main() -> std::io::Result<()> { // timestamp status_code latency remote_ip request_details let log_format = "%t | %s | %Dms | %a | \"%r\""; - HttpServer::new(|| App::new().wrap(Logger::new(log_format)).service(ping)) - .bind(("0.0.0.0", 8080))? - .run() - .await + // setup db pool + let db_url = std::env::var("LAURELIN_DB_URL").expect("LAURELIN_DB_URL"); + let manager = ConnectionManager::::new(db_url); + let pg_pool = r2d2::Pool::builder() + .build(manager) + .expect("failed to create pool"); + + HttpServer::new(move || { + App::new() + .app_data(web::Data::new(pg_pool.clone())) + .wrap(Logger::new(log_format)) + .service(ping) + }) + .bind(("0.0.0.0", 8080))? + .run() + .await } -- 2.44.1