From 78e8ea4aa487c402ea45d54f4e42a5c2b116728d Mon Sep 17 00:00:00 2001 From: Ruidy Date: Wed, 30 Dec 2020 01:57:26 +0100 Subject: [PATCH] mutable state --- src/main.rs | 37 ++++++++++++++++++++----------------- src/task/routes.rs | 10 +++++----- src/task/types.rs | 3 ++- 3 files changed, 27 insertions(+), 23 deletions(-) diff --git a/src/main.rs b/src/main.rs index 19db48b..fe5fe67 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ -// #![deny(missing_docs)] +use std::sync::Mutex; -use actix_web::{middleware, App, HttpServer}; +use actix_web::{middleware, web, App, HttpServer}; use env_logger::Env; mod task; @@ -9,23 +9,26 @@ mod task; #[actix_web::main] async fn main() -> std::io::Result<()> { env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); - HttpServer::new(|| { + + let tasks = web::Data::new(task::TaskList { + tasks: Mutex::new(vec![ + task::Task { + id: 0, + title: "Learn Rust".to_string(), + is_completed: true, + }, + task::Task { + id: 1, + title: "Learn Actix".to_string(), + is_completed: false, + }, + ]), + }); + + HttpServer::new(move || { App::new() .wrap(middleware::Logger::default()) - .data(task::TaskList { - tasks: vec![ - task::Task { - id: 0, - title: "Learn Rust".to_string(), - is_completed: false, - }, - task::Task { - id: 1, - title: "Learn Actix".to_string(), - is_completed: false, - }, - ], - }) + .app_data(tasks.clone()) .configure(task::init) }) .bind("127.0.0.1:8000")? diff --git a/src/task/routes.rs b/src/task/routes.rs index 780b5dc..eb86218 100644 --- a/src/task/routes.rs +++ b/src/task/routes.rs @@ -29,17 +29,17 @@ async fn get_task( web::Path(id): web::Path, data: web::Data, ) -> Result { - let task = &data.tasks[id]; + let task = &data.tasks.lock().unwrap()[id]; Ok(HttpResponse::Ok().json(task)) } /// Creates and stores a new `Task` #[post("/")] async fn add_task(form: web::Form, data: web::Data) -> Result { - let id = data.tasks.len(); + let id = data.tasks.lock().unwrap().len(); let new_task = Task::new(id, form.title.clone()); - // data.tasks.push(new_task); - Ok(HttpResponse::Ok().json(new_task)) + data.tasks.lock().unwrap().push(new_task); + Ok(HttpResponse::Ok().status(StatusCode::CREATED).json(id)) } /// Closes the given task if open, otherwise return an bad request @@ -48,7 +48,7 @@ async fn close_task( web::Path(id): web::Path, data: web::Data, ) -> Result { - let task = &data.tasks[id]; + let task = &data.tasks.lock().unwrap()[id]; if task.is_completed { Ok(HttpResponse::new(StatusCode::BAD_REQUEST)) } else { diff --git a/src/task/types.rs b/src/task/types.rs index bded8d9..37cd98e 100644 --- a/src/task/types.rs +++ b/src/task/types.rs @@ -1,4 +1,5 @@ use serde::{Deserialize, Serialize}; +use std::sync::Mutex; /// Task model #[derive(Serialize, Deserialize)] @@ -39,5 +40,5 @@ pub struct NewTask { /// The actual task container. #[derive(Serialize, Deserialize)] pub struct TaskList { - pub tasks: Vec, + pub tasks: Mutex>, }