refactor(main): Use actix-web extractor pattern

This commit is contained in:
Vincent Ambo 2018-04-08 18:42:01 +02:00
parent 316036b0a8
commit a1a6b77fdf

View file

@ -24,6 +24,7 @@ pub mod db;
use actix::prelude::*; use actix::prelude::*;
use actix_web::*; use actix_web::*;
use actix_web::http::Method;
use diesel::pg::PgConnection; use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool}; use diesel::r2d2::{ConnectionManager, Pool};
@ -48,13 +49,13 @@ fn render_threads(tpl: &tera::Tera, threads: Vec<Thread>) -> String {
tpl.render("index.html", &ctx).expect("Oh no") tpl.render("index.html", &ctx).expect("Oh no")
} }
fn forum_index(req: HttpRequest<AppState>) -> FutureResponse<HttpResponse> { fn forum_index(state: State<AppState>) -> FutureResponse<HttpResponse> {
req.state().db.send(ListThreads) state.db.send(ListThreads)
.from_err() .from_err()
.and_then(move |res| match res { .and_then(move |res| match res {
Ok(threads) => Ok(HttpResponse::Ok() Ok(threads) => Ok(HttpResponse::Ok()
.content_type("text/html") .content_type("text/html")
.body(render_threads(&req.state().tera, threads))), .body(render_threads(&state.tera, threads))),
Err(err) => { Err(err) => {
error!("Error loading threads: {}", err); error!("Error loading threads: {}", err);
Ok(HttpResponse::InternalServerError().into()) Ok(HttpResponse::InternalServerError().into())
@ -74,14 +75,15 @@ fn render_thread(tpl: &tera::Tera, thread: Thread, posts: Vec<Post>) -> HttpResp
.body(body) .body(body)
} }
fn forum_thread(req: HttpRequest<AppState>) -> FutureResponse<HttpResponse> { fn forum_thread(state: State<AppState>, thread_id: Path<i32>)
let thread_id = req.match_info().query("id").unwrap(); -> FutureResponse<HttpResponse> {
req.state().db.send(GetThread(thread_id)) let id = thread_id.into_inner();
state.db.send(GetThread(id))
.from_err() .from_err()
.and_then(move |res| match res { .and_then(move |res| match res {
Ok((thread, posts)) => Ok(render_thread(&req.state().tera, thread, posts)), Ok((thread, posts)) => Ok(render_thread(&state.tera, thread, posts)),
Err(err) => { Err(err) => {
error!("Error loading thread {}: {}", thread_id, err); error!("Error loading thread {}: {}", id, err);
Ok(HttpResponse::InternalServerError().into()) Ok(HttpResponse::InternalServerError().into())
} }
}) })
@ -110,8 +112,8 @@ fn main() {
App::with_state(AppState { db: db_addr.clone(), tera }) App::with_state(AppState { db: db_addr.clone(), tera })
.middleware(middleware::Logger::default()) .middleware(middleware::Logger::default())
.route("/", http::Method::GET, &forum_index) .resource("/", |r| r.method(Method::GET).with(forum_index))
.route("/thread/{id}", http::Method::GET, &forum_thread) .resource("/thread/{id}", |r| r.method(Method::GET).with2(forum_thread))
}).bind("127.0.0.1:4567").unwrap().start(); }).bind("127.0.0.1:4567").unwrap().start();
let _ = sys.run(); let _ = sys.run();