DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: a036b2fd222ab7dfa67a1b2f1b505d4929739905 deck-builder/api/src/main.rs -rw-r--r-- 1.5 KiB
a036b2fdJonni Liljamo chore(server): add needed beby deps 1 year, 10 months ago
                                                                                
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
/*
 * This file is part of laurelin/api
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

use actix_web::{get, middleware::Logger, web, App, HttpResponse, HttpServer, Responder};

use diesel::{
    self,
    r2d2::{self, ConnectionManager},
    PgConnection,
};
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};

type PgPool = r2d2::Pool<ConnectionManager<PgConnection>>;

const MIGRATIONS: EmbeddedMigrations = embed_migrations!();

#[get("/ping")]
async fn ping() -> impl Responder {
    HttpResponse::Ok().body("pong")
}

fn run_migrations(conn: &mut PgConnection) {
    conn.run_pending_migrations(MIGRATIONS).unwrap();
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    pretty_env_logger::init();

    // timestamp status_code latency remote_ip request_details
    let log_format = "%t | %s | %Dms | %a | \"%r\"";

    // setup db pool
    let db_url = std::env::var("LAURELIN_DB_URL").expect("LAURELIN_DB_URL");
    let manager = ConnectionManager::<PgConnection>::new(db_url);
    let pg_pool = r2d2::Pool::builder()
        .build(manager)
        .expect("failed to create pool");

    // run migrations
    log::info!("running migrations");
    run_migrations(&mut pg_pool.get().unwrap());

    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
}