~starkingdoms/starkingdoms

ref: 992891fbb02a84f34814269ce200d14fcefeffcc starkingdoms/api/src/main.rs -rw-r--r-- 2.7 KiB
992891fb — ghostlyzsh Merge branch 'bevy_rewrite' of https://gitlab.com/starkingdoms.tk/starkingdoms.tk into bevy_rewrite 2 years 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use crate::config::CONFIG;
use crate::error::{APIError, APIErrorsResponse};
use actix_cors::Cors;
use actix_request_identifier::RequestIdentifier;
use actix_web::http::header::HeaderValue;
use actix_web::web::{Data, JsonConfig};
use actix_web::{App, HttpResponse, HttpServer};
use log::{info, Level};
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use starkingdoms_api_migration::{Migrator, MigratorTrait};
use std::error::Error;
use std::time::Duration;
use tera::Tera;

pub mod config;
pub mod error;
pub mod routes;

pub struct AppState {
    pub conn: DatabaseConnection,
    pub templates: Tera,
}

#[actix_web::main]
async fn main() -> Result<(), Box<dyn Error>> {
    simple_logger::init_with_level(Level::Debug).unwrap();

    info!("Connecting to database at {}...", CONFIG.database.url);

    let mut opt = ConnectOptions::new(CONFIG.database.url.clone());
    opt.max_connections(CONFIG.database.max_connections)
        .min_connections(CONFIG.database.min_connections)
        .connect_timeout(Duration::from_secs(CONFIG.database.connect_timeout))
        .acquire_timeout(Duration::from_secs(CONFIG.database.acquire_timeout))
        .idle_timeout(Duration::from_secs(CONFIG.database.idle_timeout))
        .max_lifetime(Duration::from_secs(CONFIG.database.max_lifetime))
        .sqlx_logging(CONFIG.database.sqlx_logging)
        .sqlx_logging_level(log::LevelFilter::Info);

    let db = Database::connect(opt).await?;

    info!("Performing database migration...");
    Migrator::up(&db, None).await?;

    info!("Loading templates...");
    let tera = Tera::new("templates/**/*.tera")?;

    let data = Data::new(AppState {
        conn: db,
        templates: tera,
    });

    HttpServer::new(move || {
        App::new()
            .wrap(Cors::permissive())
            .app_data(data.clone())
            .app_data(JsonConfig::default().error_handler(|err, _req| {
                let api_error: APIError = (&err).into();
                actix_web::error::InternalError::from_response(
                    err,
                    HttpResponse::BadRequest().json(APIErrorsResponse {
                        errors: vec![api_error],
                    }),
                )
                .into()
            }))
            .wrap(RequestIdentifier::with_generator(|| {
                HeaderValue::from_str(&ulid::Ulid::new().to_string()).unwrap()
            }))
            .service(routes::select_realm::select_realm)
            .service(routes::callback::callback)
            .service(routes::beamin::beam_in)
            .service(routes::beamout::beam_out)
            .service(routes::server_list::server_list)
            .service(actix_files::Files::new("/static", "static"))
    })
    .bind(CONFIG.server.bind)?
    .run()
    .await?;

    Ok(())
}