trifid/trifid-api/src/main.rs

67 lines
2.2 KiB
Rust
Raw Normal View History

2023-02-03 02:39:41 +00:00
use std::error::Error;
2023-04-02 16:08:36 +00:00
use std::time::Duration;
2023-04-02 19:25:52 +00:00
use actix_request_identifier::RequestIdentifier;
2023-04-02 16:08:36 +00:00
use actix_web::{App, HttpResponse, HttpServer, post, web::{Data, Json, JsonConfig}};
use log::{error, info, Level};
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use serde::{Serialize, Deserialize};
2023-04-02 17:06:16 +00:00
use trifid_api_migration::{Migrator, MigratorTrait};
2023-04-02 16:08:36 +00:00
use crate::config::CONFIG;
2023-04-02 17:06:16 +00:00
use crate::error::{APIError, APIErrorsResponse};
2023-04-02 19:25:52 +00:00
use crate::tokens::random_id_no_id;
2023-02-20 18:42:15 +00:00
2023-04-02 16:08:36 +00:00
pub mod config;
2023-04-02 17:06:16 +00:00
pub mod routes;
pub mod error;
2023-04-02 19:25:52 +00:00
pub mod tokens;
pub mod timers;
pub struct AppState {
pub conn: DatabaseConnection
}
2023-02-20 18:42:15 +00:00
2023-04-02 16:08:36 +00:00
#[actix_web::main]
2023-02-03 02:39:41 +00:00
async fn main() -> Result<(), Box<dyn Error>> {
2023-04-02 16:08:36 +00:00
simple_logger::init_with_level(Level::Debug).unwrap();
2023-02-03 02:39:41 +00:00
2023-04-02 16:08:36 +00:00
info!("Connecting to database at {}...", CONFIG.database.url);
2023-02-03 02:39:41 +00:00
2023-04-02 16:08:36 +00:00
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);
2023-02-03 02:39:41 +00:00
2023-04-02 16:08:36 +00:00
let db = Database::connect(opt).await?;
2023-02-03 02:39:41 +00:00
2023-04-02 17:06:16 +00:00
info!("Performing database migration...");
Migrator::up(&db, None).await?;
2023-04-02 19:25:52 +00:00
let data = Data::new(AppState {
conn: db
});
2023-04-02 17:06:16 +00:00
HttpServer::new(move || {
App::new()
.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()
}))
2023-04-02 19:25:52 +00:00
.wrap(RequestIdentifier::with_generator(random_id_no_id))
2023-04-02 17:06:16 +00:00
}).bind(CONFIG.server.bind)?.run().await?;
2023-02-03 02:39:41 +00:00
Ok(())
2023-04-02 16:08:36 +00:00
}