aboutsummaryrefslogblamecommitdiffstats
path: root/src/controllers/home_controller.rs
blob: cc0fa8a16f1e085f5bd4ec8eabd919e48629afd1 (plain) (tree)
1
2
3
4
5
6
7
8
9
                                                                     
                 

                                                                
                         
                       
                          
 
                      
                                    
                      
                                 

 
                                        

                                 

                                                                            
                                       
              
                                
                                       
                            
                                                      

                           
     


                                        
                                                
                              
 




                                                              

                                                             
 
 
                               
                                           
 
#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
use models::Post;
use posts_controller::ShowPostTemplate;
use rocket::{request::FlashMessage, response::NamedFile, Route};
use rocket_contrib::Json;
use std::path::PathBuf;
use utils::{DbConn, Page};

#[derive(BartDisplay)]
#[template = "templates/index.html"]
struct IndexTemplate {
    posts: Vec<ShowPostTemplate>,
}

implement_responder_for!(IndexTemplate);

#[get("/", format = "text/html")]
fn index(flash: Option<FlashMessage>, conn: DbConn) -> Page<IndexTemplate> {
    Page {
        title: String::from("Bloggen"),
        flash,
        content: IndexTemplate {
            posts: Post::get_all(&conn)
                .into_iter()
                .map(|p| ShowPostTemplate { post: p })
                .collect(),
        },
    }
}

#[get("/", format = "application/json")]
fn index_json(conn: DbConn) -> Json<Vec<Post>> {
    Json(Post::get_all(&conn))
}

//
// Serve files from the public directory if no routes matches.
//
#[get("/<file..>", rank = 99)]
fn public_file(file: PathBuf) -> Option<NamedFile> {
    NamedFile::open(PathBuf::from("public/").join(file)).ok()
}

pub fn routes() -> Vec<Route> {
    routes![index, index_json, public_file]
}