Add an error management in db module
[recipes.git] / backend / src / main.rs
index fcb8e12..daeed7a 100644 (file)
@@ -1,16 +1,13 @@
-extern crate actix_web;
-extern crate listenfd;
-extern crate askama;
+use std::io::prelude::*;
+use std::{fs::File, env::args};
 
-use listenfd::ListenFd;
 use actix_files as fs;
-use actix_web::{web, middleware, App, HttpServer, HttpResponse, Result, web::Query};
-use askama::Template;
+use actix_web::{get, web, Responder, middleware, App, HttpServer, HttpResponse, HttpRequest, web::Query};
 
-use std::io::prelude::*;
+use askama::Template;
+use listenfd::ListenFd;
 use ron::de::from_reader;
 use serde::Deserialize;
-use std::{fs::File, env::args};
 
 use itertools::Itertools;
 
@@ -18,9 +15,16 @@ mod consts;
 mod db;
 
 #[derive(Template)]
-#[template(path = "main.html")]
-struct MainTemplate<'a> {
-    test: &'a str,
+#[template(path = "home.html")]
+struct HomeTemplate {
+    recipes: Vec<db::Recipe>
+}
+
+#[derive(Template)]
+#[template(path = "view_recipe.html")]
+struct ViewRecipeTemplate {
+    recipes: Vec<db::Recipe>,
+    current_recipe: db::Recipe
 }
 
 #[derive(Deserialize)]
@@ -28,12 +32,14 @@ pub struct Request {
    m: Option<String>
 }
 
-fn main_page(query: Query<Request>) -> Result<HttpResponse> {
-
-    let main_template = MainTemplate { test: &"test" };
+#[get("/")]
+async fn home_page(req: HttpRequest) -> impl Responder {
+    HomeTemplate { recipes: vec![ db::Recipe { title: String::from("Saumon en croûte feuilletée"), id: 1 }, db::Recipe { title: String::from("Croissant au jambon"), id: 2 } ] }
+}
 
-    let s = main_template.render().unwrap();
-    Ok(HttpResponse::Ok().content_type("text/html").body(s))
+#[get("/recipe/view/{id}")]
+async fn view_page(req: HttpRequest, path: web::Path<(i32,)>) -> impl Responder {
+    ViewRecipeTemplate { recipes: vec![ db::Recipe { title: String::from("Saumon en croûte feuilletée"), id: 1 }, db::Recipe { title: String::from("Croissant au jambon"), id: 2 } ], current_recipe: db::Recipe { title: String::from("Saumon en croûte feuilletée"), id: 1 } }
 }
 
 #[derive(Debug, Deserialize)]
@@ -47,10 +53,11 @@ fn get_exe_name() -> String {
     first_arg[first_arg.rfind(sep).unwrap()+1..].to_string()
 }
 
-fn main() -> std::io::Result<()> {
+#[actix_rt::main]
+async fn main() -> std::io::Result<()> {
     if process_args() { return Ok(()) }
 
-    println!("Starting RUP as web server...");
+    println!("Starting Recipes as web server...");
 
     let config: Config = {
         let f = File::open(consts::FILE_CONF).unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
@@ -62,7 +69,9 @@ fn main() -> std::io::Result<()> {
 
     println!("Configuration: {:?}", config);
 
-    let database_connection = db::create_or_update();
+    // let database_connection = db::create_or_update();
+
+    std::env::set_var("RUST_LOG", "actix_web=info");
 
     let mut listenfd = ListenFd::from_env();
     let mut server =
@@ -70,8 +79,8 @@ fn main() -> std::io::Result<()> {
             || {
                 App::new()
                     .wrap(middleware::Compress::default())
-                    .wrap(middleware::Logger::default())
-                    .service(web::resource("/").to(main_page))
+                    .service(home_page)
+                    .service(view_page)
                     .service(fs::Files::new("/static", "static").show_files_listing())
             }
         );
@@ -83,7 +92,7 @@ fn main() -> std::io::Result<()> {
             server.bind(&format!("0.0.0.0:{}", config.port)).unwrap()
         };
 
-    server.run()
+    server.run().await
 }
 
 fn process_args() -> bool {
@@ -98,7 +107,10 @@ fn process_args() -> bool {
         print_usage();
         return true
     } else if args.iter().any(|arg| arg == "--test") {
-        let database_connection = db::create_or_update();
+        match db::Connection::new() {
+            Ok(_) => (),
+            Err(error) => println!("Error: {:?}", error)
+        }
         return true
     }