Add asynchronous call to database.
[recipes.git] / backend / src / main.rs
1 use actix_files as fs;
2 use actix_web::{web, middleware, App, HttpServer};
3 use chrono::prelude::*;
4 use clap::Parser;
5 use log::error;
6
7 use data::db;
8
9 mod consts;
10 mod utils;
11 mod data;
12 mod hash;
13 mod model;
14 mod user;
15 mod email;
16 mod config;
17 mod services;
18
19 #[actix_web::main]
20 async fn main() -> std::io::Result<()> {
21 if process_args() { return Ok(()) }
22
23 std::env::set_var("RUST_LOG", "info,actix_web=info");
24 env_logger::init();
25
26 println!("Starting Recipes as web server...");
27
28 let config = web::Data::new(config::load());
29 let port = config.as_ref().port;
30
31 println!("Configuration: {:?}", config);
32
33 let db_connection = web::Data::new(db::Connection::new().unwrap());
34
35 let server =
36 HttpServer::new(move || {
37 App::new()
38 .wrap(middleware::Logger::default())
39 .wrap(middleware::Compress::default())
40 .app_data(db_connection.clone())
41 .app_data(config.clone())
42 .service(services::home_page)
43 .service(services::sign_up_get)
44 .service(services::sign_up_post)
45 .service(services::sign_up_check_email)
46 .service(services::sign_up_validation)
47 .service(services::sign_in_get)
48 .service(services::sign_in_post)
49 .service(services::sign_out)
50 .service(services::view_recipe)
51 .service(fs::Files::new("/static", "static"))
52 .default_service(web::to(services::not_found))
53 });
54 //.workers(1);
55
56 server.bind(&format!("0.0.0.0:{}", port))?.run().await
57 }
58
59 #[derive(Parser, Debug)]
60 struct Args {
61 #[arg(long)]
62 dbtest: bool
63 }
64
65 fn process_args() -> bool {
66 let args = Args::parse();
67
68 if args.dbtest {
69 match db::Connection::new() {
70 Ok(con) => {
71 if let Err(error) = con.execute_file("sql/data_test.sql") {
72 eprintln!("{}", error);
73 }
74 // Set the creation datetime to 'now'.
75 con.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc::now()]).unwrap();
76 },
77 Err(error) => {
78 eprintln!("{}", error);
79 },
80 }
81
82 return true;
83 }
84
85 false
86 }