From 6e56f8e729551ff14b7a72ca889b8dd38999fb2d Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Sun, 8 Apr 2018 18:02:01 +0200 Subject: [PATCH] feat(main/templates): Add barebones single-thread view --- src/main.rs | 28 +++++++++++++++++++++++++++- src/models.rs | 2 +- templates/index.html | 2 +- templates/thread.html | 14 ++++++++++++++ 4 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 templates/thread.html diff --git a/src/main.rs b/src/main.rs index 419829b3e..b26954d42 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,7 +30,7 @@ use diesel::r2d2::{ConnectionManager, Pool}; use std::env; use db::*; use futures::Future; -use models::Thread; +use models::*; /// Represents the state carried by the web server actors. struct AppState { @@ -63,6 +63,31 @@ fn forum_index(req: HttpRequest) -> FutureResponse { .responder() } +fn render_thread(tpl: &tera::Tera, thread: Thread, posts: Vec) -> HttpResponse { + let mut ctx = tera::Context::new(); + ctx.add("thread", &thread); + ctx.add("posts", &posts); + + let body = tpl.render("thread.html", &ctx).expect("Oh no"); + HttpResponse::Ok() + .content_type("text/html") + .body(body) +} + +fn forum_thread(req: HttpRequest) -> FutureResponse { + let thread_id = req.match_info().query("id").unwrap(); + req.state().db.send(GetThread(thread_id)) + .from_err() + .and_then(move |res| match res { + Ok((thread, posts)) => Ok(render_thread(&req.state().tera, thread, posts)), + Err(err) => { + error!("Error loading thread {}: {}", thread_id, err); + Ok(HttpResponse::InternalServerError().into()) + } + }) + .responder() +} + fn main() { env_logger::init(); @@ -86,6 +111,7 @@ fn main() { App::with_state(AppState { db: db_addr.clone(), tera }) .middleware(middleware::Logger::default()) .route("/", http::Method::GET, &forum_index) + .route("/thread/{id}", http::Method::GET, &forum_thread) }).bind("127.0.0.1:4567").unwrap().start(); let _ = sys.run(); diff --git a/src/models.rs b/src/models.rs index 929bd0507..74b386a19 100644 --- a/src/models.rs +++ b/src/models.rs @@ -8,7 +8,7 @@ pub struct Thread { pub posted: DateTime, } -#[derive(Queryable)] +#[derive(Queryable, Serialize)] pub struct Post { pub id: i32, pub thread: i32, diff --git a/templates/index.html b/templates/index.html index 566715248..9faee49ca 100644 --- a/templates/index.html +++ b/templates/index.html @@ -7,7 +7,7 @@

Welcome to Converse

    {% for thread in threads -%} -
  • {{ thread.title }} (posted at {{ thread.posted }})
  • +
  • {{ thread.title }} (posted at {{ thread.posted }})
  • {%- endfor %}
diff --git a/templates/thread.html b/templates/thread.html new file mode 100644 index 000000000..e841668bf --- /dev/null +++ b/templates/thread.html @@ -0,0 +1,14 @@ + + + + Converse: {{ thread.title }} + + +

{{ thread.title }}

+ +

{{ thread.body }}
Posted at {{ thread.posted }}

+ {% for post in posts -%} +
  • {{ post.body }}
    Posted at {{ post.posted }}

    + {%- endfor %} + +