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









                          
                         
                       
                                       


                                    
                      
                                

 
                                        

                                 

                                                                            
                                       
                     
                                
                                                  

                                                      

         


                                        

                                                
 




                                                              

                                                             
 
 
                               





                   
use models::Post;
use utils::{
    DbConn,
    Page
};
use rocket::{
    response::NamedFile,
    request::FlashMessage,
    Route
};
use rocket_contrib::Json;
use std::path::PathBuf;
use posts_controller::ShowPostTemplate;

#[derive(BartDisplay, Serialize)]
#[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: 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
    ]
}