summaryrefslogtreecommitdiffstats
path: root/service-person/src/main.rs
blob: 3c5dc7453adffba9de4e2053ca5f4e999e720af6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_migrations;

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::*;

embed_migrations!("migrations");

type DbPool = Pool<ConnectionManager<PgConnection>>;

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<Person>) -> Result<HttpResponse> {
    log::debug!("Creating person = {:?}", person);
    Ok(HttpResponse::Ok().finish())
}


#[actix_web::main]
async fn main() -> anyhow::Result<()> {
    env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
    let bind = std::env::var("HOST").expect("environment: HOST variable not set");
    let port = std::env::var("PORT")
        .as_ref()
        .map(|p| u16::from_str(p))
        .expect("environment: PORT variable not set")
        .context("Failed to parse port as integer")?;

    let db_connection_pool = establish_connection();

    {
        let conn = db_connection_pool.get().expect("Failed to get connection from pool");
        embedded_migrations::run_with_output(&conn, &mut std::io::stdout());
    } // drop `conn` here

    HttpServer::new(move || {
        App::new()
            .data(db_connection_pool.clone())
            .route("/create", web::post().to(create_person))
    })
    .bind(format!("{}:{}", bind, port))?
    .run()
    .await
    .map_err(anyhow::Error::from)
}