1
0
mirror of https://github.com/actix/examples synced 2025-02-02 09:39:03 +01:00

upgrade actix_todo

This commit is contained in:
Nikolay Kim 2019-03-10 18:23:44 -07:00
parent 52c12f264a
commit 17744bbfe4
6 changed files with 137 additions and 224 deletions

View File

@ -2,10 +2,13 @@
authors = ["Dan Munckton <dangit@munckfish.net>"] authors = ["Dan Munckton <dangit@munckfish.net>"]
name = "actix-todo" name = "actix-todo"
version = "0.1.0" version = "0.1.0"
workspace = ".."
edition = "2018"
[dependencies] [dependencies]
actix = "0.7.3" actix-web = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
actix-web = "0.7.4" actix-files = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
actix-session = { git="https://github.com/actix/actix-web.git", branch = "1.0" }
dotenv = "0.13.0" dotenv = "0.13.0"
env_logger = "0.5.10" env_logger = "0.5.10"
futures = "0.1.22" futures = "0.1.22"

View File

@ -1,42 +1,34 @@
use actix::prelude::Addr; use actix_files::NamedFile;
use actix_web::middleware::Response; use actix_session::Session;
use actix_web::{ use actix_web::middleware::ErrorHandlerResponse;
error, fs::NamedFile, http, AsyncResponder, Form, FutureResponse, HttpRequest, use actix_web::{dev, error, http, web, Error, HttpResponse, Responder, Result};
HttpResponse, Path, Responder, Result, use futures::future::{err, Either, Future, IntoFuture};
};
use futures::{future, Future};
use tera::{Context, Tera}; use tera::{Context, Tera};
use db::{AllTasks, CreateTask, DbExecutor, DeleteTask, ToggleTask}; use crate::db;
use session::{self, FlashMessage}; use crate::session::{self, FlashMessage};
pub struct AppState { pub fn index(
pub template: Tera, pool: web::State<db::PgPool>,
pub db: Addr<DbExecutor>, tmpl: web::State<Tera>,
} session: Session,
) -> impl Future<Item = HttpResponse, Error = Error> {
pub fn index(req: HttpRequest<AppState>) -> FutureResponse<HttpResponse> { web::block(move || db::get_all_tasks(&pool))
req.state()
.db
.send(AllTasks)
.from_err() .from_err()
.and_then(move |res| match res { .then(move |res| match res {
Ok(tasks) => { Ok(tasks) => {
let mut context = Context::new(); let mut context = Context::new();
context.add("tasks", &tasks); context.insert("tasks", &tasks);
//Session is set during operations on other endpoints //Session is set during operations on other endpoints
//that can redirect to index //that can redirect to index
if let Some(flash) = session::get_flash(&req)? { if let Some(flash) = session::get_flash(&session)? {
context.add("msg", &(flash.kind, flash.message)); context.insert("msg", &(flash.kind, flash.message));
session::clear_flash(&req); session::clear_flash(&session);
} }
let rendered = req let rendered =
.state() tmpl.render("index.html.tera", &context).map_err(|e| {
.template
.render("index.html.tera", &context)
.map_err(|e| {
error::ErrorInternalServerError(e.description().to_owned()) error::ErrorInternalServerError(e.description().to_owned())
})?; })?;
@ -44,7 +36,6 @@ pub fn index(req: HttpRequest<AppState>) -> FutureResponse<HttpResponse> {
} }
Err(e) => Err(e), Err(e) => Err(e),
}) })
.responder()
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@ -53,35 +44,34 @@ pub struct CreateForm {
} }
pub fn create( pub fn create(
(req, params): (HttpRequest<AppState>, Form<CreateForm>), params: web::Form<CreateForm>,
) -> FutureResponse<HttpResponse> { pool: web::State<db::PgPool>,
session: Session,
) -> impl Future<Item = HttpResponse, Error = Error> {
if params.description.is_empty() { if params.description.is_empty() {
future::lazy(move || { Either::A(
session::set_flash( session::set_flash(
&req, &session,
FlashMessage::error("Description cannot be empty"), FlashMessage::error("Description cannot be empty"),
)?; )
Ok(redirect_to("/")) .map(|_| redirect_to("/"))
}) .into_future(),
.responder() )
} else { } else {
req.state() Either::B(
.db web::block(move || db::create_task(params.into_inner().description, &pool))
.send(CreateTask { .from_err()
description: params.description.clone(), .then(move |res| match res {
}) Ok(_) => {
.from_err() session::set_flash(
.and_then(move |res| match res { &session,
Ok(_) => { FlashMessage::success("Task successfully added"),
session::set_flash( )?;
&req, Ok(redirect_to("/"))
FlashMessage::success("Task successfully added"), }
)?; Err(e) => Err(e),
Ok(redirect_to("/")) }),
} )
Err(e) => Err(e),
})
.responder()
} }
} }
@ -96,49 +86,50 @@ pub struct UpdateForm {
} }
pub fn update( pub fn update(
(req, params, form): (HttpRequest<AppState>, Path<UpdateParams>, Form<UpdateForm>), db: web::State<db::PgPool>,
) -> FutureResponse<HttpResponse> { params: web::Path<UpdateParams>,
form: web::Form<UpdateForm>,
session: Session,
) -> impl Future<Item = HttpResponse, Error = Error> {
match form._method.as_ref() { match form._method.as_ref() {
"put" => toggle(req, params), "put" => Either::A(Either::A(toggle(db, params))),
"delete" => delete(req, params), "delete" => Either::A(Either::B(delete(db, params, session))),
unsupported_method => { unsupported_method => {
let msg = format!("Unsupported HTTP method: {}", unsupported_method); let msg = format!("Unsupported HTTP method: {}", unsupported_method);
future::err(error::ErrorBadRequest(msg)).responder() Either::B(err(error::ErrorBadRequest(msg)))
} }
} }
} }
fn toggle( fn toggle(
req: HttpRequest<AppState>, pool: web::State<db::PgPool>,
params: Path<UpdateParams>, params: web::Path<UpdateParams>,
) -> FutureResponse<HttpResponse> { ) -> impl Future<Item = HttpResponse, Error = Error> {
req.state() web::block(move || db::toggle_task(params.id, &pool))
.db
.send(ToggleTask { id: params.id })
.from_err() .from_err()
.and_then(move |res| match res { .then(move |res| match res {
Ok(_) => Ok(redirect_to("/")), Ok(_) => Ok(redirect_to("/")),
Err(e) => Err(e), Err(e) => Err(e),
}) })
.responder()
} }
fn delete( fn delete(
req: HttpRequest<AppState>, pool: web::State<db::PgPool>,
params: Path<UpdateParams>, params: web::Path<UpdateParams>,
) -> FutureResponse<HttpResponse> { session: Session,
req.state() ) -> impl Future<Item = HttpResponse, Error = Error> {
.db web::block(move || db::delete_task(params.id, &pool))
.send(DeleteTask { id: params.id })
.from_err() .from_err()
.and_then(move |res| match res { .then(move |res| match res {
Ok(_) => { Ok(_) => {
session::set_flash(&req, FlashMessage::success("Task was deleted."))?; session::set_flash(
&session,
FlashMessage::success("Task was deleted."),
)?;
Ok(redirect_to("/")) Ok(redirect_to("/"))
} }
Err(e) => Err(e), Err(e) => Err(e),
}) })
.responder()
} }
fn redirect_to(location: &str) -> HttpResponse { fn redirect_to(location: &str) -> HttpResponse {
@ -147,32 +138,31 @@ fn redirect_to(location: &str) -> HttpResponse {
.finish() .finish()
} }
pub fn bad_request<S: 'static>( pub fn bad_request<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
req: &HttpRequest<S>,
resp: HttpResponse,
) -> Result<Response> {
let new_resp = NamedFile::open("static/errors/400.html")? let new_resp = NamedFile::open("static/errors/400.html")?
.set_status_code(resp.status()) .set_status_code(res.status())
.respond_to(req)?; .respond_to(res.request())?;
Ok(Response::Done(new_resp)) Ok(ErrorHandlerResponse::Response(
res.into_response(new_resp.into_body()),
))
} }
pub fn not_found<S: 'static>( pub fn not_found<B>(res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
req: &HttpRequest<S>,
resp: HttpResponse,
) -> Result<Response> {
let new_resp = NamedFile::open("static/errors/404.html")? let new_resp = NamedFile::open("static/errors/404.html")?
.set_status_code(resp.status()) .set_status_code(res.status())
.respond_to(req)?; .respond_to(res.request())?;
Ok(Response::Done(new_resp)) Ok(ErrorHandlerResponse::Response(
res.into_response(new_resp.into_body()),
))
} }
pub fn internal_server_error<S: 'static>( pub fn internal_server_error<B>(
req: &HttpRequest<S>, res: dev::ServiceResponse<B>,
resp: HttpResponse, ) -> Result<ErrorHandlerResponse<B>> {
) -> Result<Response> {
let new_resp = NamedFile::open("static/errors/500.html")? let new_resp = NamedFile::open("static/errors/500.html")?
.set_status_code(resp.status()) .set_status_code(res.status())
.respond_to(req)?; .respond_to(res.request())?;
Ok(Response::Done(new_resp)) Ok(ErrorHandlerResponse::Response(
res.into_response(new_resp.into_body()),
))
} }

View File

@ -1,13 +1,11 @@
use std::ops::Deref; use std::ops::Deref;
use actix::prelude::{Actor, Handler, Message, SyncContext};
use actix_web::{error, Error};
use diesel::pg::PgConnection; use diesel::pg::PgConnection;
use diesel::r2d2::{ConnectionManager, Pool, PoolError, PooledConnection}; use diesel::r2d2::{ConnectionManager, Pool, PoolError, PooledConnection};
use model::{NewTask, Task}; use crate::model::{NewTask, Task};
type PgPool = Pool<ConnectionManager<PgConnection>>; pub type PgPool = Pool<ConnectionManager<PgConnection>>;
type PgPooledConnection = PooledConnection<ConnectionManager<PgConnection>>; type PgPooledConnection = PooledConnection<ConnectionManager<PgConnection>>;
pub fn init_pool(database_url: &str) -> Result<PgPool, PoolError> { pub fn init_pool(database_url: &str) -> Result<PgPool, PoolError> {
@ -15,86 +13,29 @@ pub fn init_pool(database_url: &str) -> Result<PgPool, PoolError> {
Pool::builder().build(manager) Pool::builder().build(manager)
} }
pub struct DbExecutor(pub PgPool); fn get_conn(pool: &PgPool) -> Result<PgPooledConnection, &'static str> {
pool.get().map_err(|_| "can get connection")
impl DbExecutor {
pub fn get_conn(&self) -> Result<PgPooledConnection, Error> {
self.0.get().map_err(|e| error::ErrorInternalServerError(e))
}
} }
impl Actor for DbExecutor { pub fn get_all_tasks(pool: &PgPool) -> Result<Vec<Task>, &'static str> {
type Context = SyncContext<Self>; Task::all(get_conn(pool)?.deref()).map_err(|_| "Error inserting task")
} }
pub struct AllTasks; pub fn create_task(todo: String, pool: &PgPool) -> Result<(), &'static str> {
let new_task = NewTask { description: todo };
impl Message for AllTasks { Task::insert(new_task, get_conn(pool)?.deref())
type Result = Result<Vec<Task>, Error>; .map(|_| ())
.map_err(|_| "Error inserting task")
} }
impl Handler<AllTasks> for DbExecutor { pub fn toggle_task(id: i32, pool: &PgPool) -> Result<(), &'static str> {
type Result = Result<Vec<Task>, Error>; Task::toggle_with_id(id, get_conn(pool)?.deref())
.map(|_| ())
fn handle(&mut self, _: AllTasks, _: &mut Self::Context) -> Self::Result { .map_err(|_| "Error inserting task")
Task::all(self.get_conn()?.deref())
.map_err(|_| error::ErrorInternalServerError("Error inserting task"))
}
} }
pub struct CreateTask { pub fn delete_task(id: i32, pool: &PgPool) -> Result<(), &'static str> {
pub description: String, Task::delete_with_id(id, get_conn(pool)?.deref())
} .map(|_| ())
.map_err(|_| "Error inserting task")
impl Message for CreateTask {
type Result = Result<(), Error>;
}
impl Handler<CreateTask> for DbExecutor {
type Result = Result<(), Error>;
fn handle(&mut self, todo: CreateTask, _: &mut Self::Context) -> Self::Result {
let new_task = NewTask {
description: todo.description,
};
Task::insert(new_task, self.get_conn()?.deref())
.map(|_| ())
.map_err(|_| error::ErrorInternalServerError("Error inserting task"))
}
}
pub struct ToggleTask {
pub id: i32,
}
impl Message for ToggleTask {
type Result = Result<(), Error>;
}
impl Handler<ToggleTask> for DbExecutor {
type Result = Result<(), Error>;
fn handle(&mut self, task: ToggleTask, _: &mut Self::Context) -> Self::Result {
Task::toggle_with_id(task.id, self.get_conn()?.deref())
.map(|_| ())
.map_err(|_| error::ErrorInternalServerError("Error inserting task"))
}
}
pub struct DeleteTask {
pub id: i32,
}
impl Message for DeleteTask {
type Result = Result<(), Error>;
}
impl Handler<DeleteTask> for DbExecutor {
type Result = Result<(), Error>;
fn handle(&mut self, task: DeleteTask, _: &mut Self::Context) -> Self::Result {
Task::delete_with_id(task.id, self.get_conn()?.deref())
.map(|_| ())
.map_err(|_| error::ErrorInternalServerError("Error inserting task"))
}
} }

View File

@ -1,8 +1,3 @@
extern crate actix;
extern crate actix_web;
extern crate dotenv;
extern crate env_logger;
extern crate futures;
#[macro_use] #[macro_use]
extern crate diesel; extern crate diesel;
#[macro_use] #[macro_use]
@ -12,12 +7,13 @@ extern crate serde_derive;
#[macro_use] #[macro_use]
extern crate tera; extern crate tera;
use actix::prelude::SyncArbiter; use std::{env, io};
use actix_web::middleware::session::{CookieSessionBackend, SessionStorage};
use actix_files as fs;
use actix_session::CookieSession;
use actix_web::middleware::{ErrorHandlers, Logger}; use actix_web::middleware::{ErrorHandlers, Logger};
use actix_web::{dev::Resource, fs, http, server, App}; use actix_web::{http, web, App, HttpServer};
use dotenv::dotenv; use dotenv::dotenv;
use std::env;
use tera::Tera; use tera::Tera;
mod api; mod api;
@ -27,29 +23,22 @@ mod schema;
mod session; mod session;
static SESSION_SIGNING_KEY: &[u8] = &[0; 32]; static SESSION_SIGNING_KEY: &[u8] = &[0; 32];
const NUM_DB_THREADS: usize = 3;
fn main() { fn main() -> io::Result<()> {
dotenv().ok(); dotenv().ok();
std::env::set_var("RUST_LOG", "actix_todo=debug,actix_web=info"); env::set_var("RUST_LOG", "actix_todo=debug,actix_web=info");
env_logger::init(); env_logger::init();
// Start the Actix system
let system = actix::System::new("todo-app");
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let pool = db::init_pool(&database_url).expect("Failed to create pool"); let pool = db::init_pool(&database_url).expect("Failed to create pool");
let addr = SyncArbiter::start(NUM_DB_THREADS, move || db::DbExecutor(pool.clone()));
let app = move || { let app = move || {
debug!("Constructing the App"); debug!("Constructing the App");
let templates: Tera = compile_templates!("templates/**/*"); let templates: Tera = compile_templates!("templates/**/*");
let session_store = SessionStorage::new( let session_store = CookieSession::signed(SESSION_SIGNING_KEY).secure(false);
CookieSessionBackend::signed(SESSION_SIGNING_KEY).secure(false),
);
let error_handlers = ErrorHandlers::new() let error_handlers = ErrorHandlers::new()
.handler( .handler(
@ -59,29 +48,20 @@ fn main() {
.handler(http::StatusCode::BAD_REQUEST, api::bad_request) .handler(http::StatusCode::BAD_REQUEST, api::bad_request)
.handler(http::StatusCode::NOT_FOUND, api::not_found); .handler(http::StatusCode::NOT_FOUND, api::not_found);
let static_files = fs::StaticFiles::new("static/") App::new()
.expect("failed constructing static files handler"); .state(templates)
.state(pool.clone())
let state = api::AppState {
template: templates,
db: addr.clone(),
};
App::with_state(state)
.middleware(Logger::default()) .middleware(Logger::default())
.middleware(session_store) .middleware(session_store)
.middleware(error_handlers) .middleware(error_handlers)
.route("/", http::Method::GET, api::index) .service(web::resource("/").route(web::get().to_async(api::index)))
.route("/todo", http::Method::POST, api::create) .service(web::resource("/todo").route(web::post().to_async(api::create)))
.resource("/todo/{id}", |r: &mut Resource<_>| { .service(
r.post().with(api::update) web::resource("/todo/{id}").route(web::post().to_async(api::update)),
}) )
.handler("/static", static_files) .service(fs::Files::new("/static", "static/"))
}; };
debug!("Starting server"); debug!("Starting server");
server::new(app).bind("localhost:8088").unwrap().start(); HttpServer::new(app).bind("localhost:8088")?.run()
// Run actix system, this method actually starts all async processes
let _ = system.run();
} }

View File

@ -2,7 +2,7 @@ use diesel;
use diesel::pg::PgConnection; use diesel::pg::PgConnection;
use diesel::prelude::*; use diesel::prelude::*;
use schema::{ use crate::schema::{
tasks, tasks,
tasks::dsl::{completed as task_completed, tasks as all_tasks}, tasks::dsl::{completed as task_completed, tasks as all_tasks},
}; };

View File

@ -1,19 +1,18 @@
use actix_session::Session;
use actix_web::error::Result; use actix_web::error::Result;
use actix_web::middleware::session::RequestSession;
use actix_web::HttpRequest;
const FLASH_KEY: &str = "flash"; const FLASH_KEY: &str = "flash";
pub fn set_flash<T>(request: &HttpRequest<T>, flash: FlashMessage) -> Result<()> { pub fn set_flash(session: &Session, flash: FlashMessage) -> Result<()> {
request.session().set(FLASH_KEY, flash) session.set(FLASH_KEY, flash)
} }
pub fn get_flash<T>(req: &HttpRequest<T>) -> Result<Option<FlashMessage>> { pub fn get_flash(session: &Session) -> Result<Option<FlashMessage>> {
req.session().get::<FlashMessage>(FLASH_KEY) session.get::<FlashMessage>(FLASH_KEY)
} }
pub fn clear_flash<T>(req: &HttpRequest<T>) { pub fn clear_flash(session: &Session) {
req.session().remove(FLASH_KEY); session.remove(FLASH_KEY);
} }
#[derive(Deserialize, Serialize)] #[derive(Deserialize, Serialize)]