Use managed state in json example.

This commit is contained in:
Crazy-Owl 2017-02-13 13:28:31 +03:00 committed by Sergio Benitez
parent 6184d94619
commit 3e063af965
3 changed files with 28 additions and 28 deletions

View File

@ -9,7 +9,6 @@ rocket_codegen = { path = "../../codegen" }
serde = "0.9" serde = "0.9"
serde_json = "0.9" serde_json = "0.9"
serde_derive = "0.9" serde_derive = "0.9"
lazy_static = "*"
[dependencies.rocket_contrib] [dependencies.rocket_contrib]
path = "../../contrib" path = "../../contrib"

View File

@ -3,13 +3,13 @@
extern crate rocket; extern crate rocket;
extern crate serde_json; extern crate serde_json;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate rocket_contrib; #[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
#[cfg(test)] mod tests; #[cfg(test)] mod tests;
use rocket_contrib::{JSON, Value}; use rocket_contrib::{JSON, Value};
use rocket::State;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Mutex; use std::sync::Mutex;
@ -17,9 +17,7 @@ use std::sync::Mutex;
type ID = usize; type ID = usize;
// We're going to store all of the messages here. No need for a DB. // We're going to store all of the messages here. No need for a DB.
lazy_static! { type MessageMap = Mutex<HashMap<ID, String>>;
static ref MAP: Mutex<HashMap<ID, String>> = Mutex::new(HashMap::new());
}
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct Message { struct Message {
@ -29,8 +27,8 @@ struct Message {
// TODO: This example can be improved by using `route` with muliple HTTP verbs. // TODO: This example can be improved by using `route` with muliple HTTP verbs.
#[post("/<id>", format = "application/json", data = "<message>")] #[post("/<id>", format = "application/json", data = "<message>")]
fn new(id: ID, message: JSON<Message>) -> JSON<Value> { fn new(id: ID, message: JSON<Message>, map: State<MessageMap>) -> JSON<Value> {
let mut hashmap = MAP.lock().expect("map lock."); let mut hashmap = map.lock().expect("map lock.");
if hashmap.contains_key(&id) { if hashmap.contains_key(&id) {
JSON(json!({ JSON(json!({
"status": "error", "status": "error",
@ -43,8 +41,8 @@ fn new(id: ID, message: JSON<Message>) -> JSON<Value> {
} }
#[put("/<id>", format = "application/json", data = "<message>")] #[put("/<id>", format = "application/json", data = "<message>")]
fn update(id: ID, message: JSON<Message>) -> Option<JSON<Value>> { fn update(id: ID, message: JSON<Message>, map: State<MessageMap>) -> Option<JSON<Value>> {
let mut hashmap = MAP.lock().unwrap(); let mut hashmap = map.lock().unwrap();
if hashmap.contains_key(&id) { if hashmap.contains_key(&id) {
hashmap.insert(id, message.0.contents); hashmap.insert(id, message.0.contents);
Some(JSON(json!({ "status": "ok" }))) Some(JSON(json!({ "status": "ok" })))
@ -54,8 +52,8 @@ fn update(id: ID, message: JSON<Message>) -> Option<JSON<Value>> {
} }
#[get("/<id>", format = "application/json")] #[get("/<id>", format = "application/json")]
fn get(id: ID) -> Option<JSON<Message>> { fn get(id: ID, map: State<MessageMap>) -> Option<JSON<Message>> {
let hashmap = MAP.lock().unwrap(); let hashmap = map.lock().unwrap();
hashmap.get(&id).map(|contents| { hashmap.get(&id).map(|contents| {
JSON(Message { JSON(Message {
id: Some(id), id: Some(id),
@ -72,9 +70,13 @@ fn not_found() -> JSON<Value> {
})) }))
} }
fn main() { fn rocket() -> rocket::Rocket {
rocket::ignite() rocket::ignite()
.mount("/message", routes![new, update, get]) .mount("/message", routes![new, update, get])
.catch(errors![not_found]) .catch(errors![not_found])
.launch(); .manage(Mutex::new(HashMap::<ID, String>::new()))
}
fn main() {
rocket().launch();
} }

View File

@ -5,21 +5,19 @@ use rocket::http::{Status, ContentType};
use rocket::Response; use rocket::Response;
macro_rules! run_test { macro_rules! run_test {
($req:expr, $test_fn:expr) => ({ ($rocket: expr, $req:expr, $test_fn:expr) => ({
let rocket = rocket::ignite()
.mount("/message", routes![super::new, super::update, super::get])
.catch(errors![super::not_found]);
let mut req = $req; let mut req = $req;
$test_fn(req.dispatch_with(&rocket)); $test_fn(req.dispatch_with($rocket));
}) })
} }
#[test] #[test]
fn bad_get_put() { fn bad_get_put() {
let rocket = rocket();
// Try to get a message with an ID that doesn't exist. // Try to get a message with an ID that doesn't exist.
let req = MockRequest::new(Get, "/message/99").header(ContentType::JSON); let req = MockRequest::new(Get, "/message/99").header(ContentType::JSON);
run_test!(req, |mut response: Response| { run_test!(&rocket, req, |mut response: Response| {
assert_eq!(response.status(), Status::NotFound); assert_eq!(response.status(), Status::NotFound);
let body = response.body().unwrap().into_string().unwrap(); let body = response.body().unwrap().into_string().unwrap();
@ -29,7 +27,7 @@ fn bad_get_put() {
// Try to get a message with an invalid ID. // Try to get a message with an invalid ID.
let req = MockRequest::new(Get, "/message/hi").header(ContentType::JSON); let req = MockRequest::new(Get, "/message/hi").header(ContentType::JSON);
run_test!(req, |mut response: Response| { run_test!(&rocket, req, |mut response: Response| {
assert_eq!(response.status(), Status::NotFound); assert_eq!(response.status(), Status::NotFound);
let body = response.body().unwrap().into_string().unwrap(); let body = response.body().unwrap().into_string().unwrap();
assert!(body.contains("error")); assert!(body.contains("error"));
@ -37,7 +35,7 @@ fn bad_get_put() {
// Try to put a message without a proper body. // Try to put a message without a proper body.
let req = MockRequest::new(Put, "/message/80").header(ContentType::JSON); let req = MockRequest::new(Put, "/message/80").header(ContentType::JSON);
run_test!(req, |response: Response| { run_test!(&rocket, req, |response: Response| {
assert_eq!(response.status(), Status::BadRequest); assert_eq!(response.status(), Status::BadRequest);
}); });
@ -46,16 +44,17 @@ fn bad_get_put() {
.header(ContentType::JSON) .header(ContentType::JSON)
.body(r#"{ "contents": "Bye bye, world!" }"#); .body(r#"{ "contents": "Bye bye, world!" }"#);
run_test!(req, |response: Response| { run_test!(&rocket, req, |response: Response| {
assert_eq!(response.status(), Status::NotFound); assert_eq!(response.status(), Status::NotFound);
}); });
} }
#[test] #[test]
fn post_get_put_get() { fn post_get_put_get() {
let rocket = rocket();
// Check that a message with ID 1 doesn't exist. // Check that a message with ID 1 doesn't exist.
let req = MockRequest::new(Get, "/message/1").header(ContentType::JSON); let req = MockRequest::new(Get, "/message/1").header(ContentType::JSON);
run_test!(req, |response: Response| { run_test!(&rocket, req, |response: Response| {
assert_eq!(response.status(), Status::NotFound); assert_eq!(response.status(), Status::NotFound);
}); });
@ -64,13 +63,13 @@ fn post_get_put_get() {
.header(ContentType::JSON) .header(ContentType::JSON)
.body(r#"{ "contents": "Hello, world!" }"#); .body(r#"{ "contents": "Hello, world!" }"#);
run_test!(req, |response: Response| { run_test!(&rocket, req, |response: Response| {
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::Ok);
}); });
// Check that the message exists with the correct contents. // Check that the message exists with the correct contents.
let req = MockRequest::new(Get, "/message/1") .header(ContentType::JSON); let req = MockRequest::new(Get, "/message/1") .header(ContentType::JSON);
run_test!(req, |mut response: Response| { run_test!(&rocket, req, |mut response: Response| {
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::Ok);
let body = response.body().unwrap().into_string().unwrap(); let body = response.body().unwrap().into_string().unwrap();
assert!(body.contains("Hello, world!")); assert!(body.contains("Hello, world!"));
@ -81,13 +80,13 @@ fn post_get_put_get() {
.header(ContentType::JSON) .header(ContentType::JSON)
.body(r#"{ "contents": "Bye bye, world!" }"#); .body(r#"{ "contents": "Bye bye, world!" }"#);
run_test!(req, |response: Response| { run_test!(&rocket, req, |response: Response| {
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::Ok);
}); });
// Check that the message exists with the updated contents. // Check that the message exists with the updated contents.
let req = MockRequest::new(Get, "/message/1") .header(ContentType::JSON); let req = MockRequest::new(Get, "/message/1") .header(ContentType::JSON);
run_test!(req, |mut response: Response| { run_test!(&rocket, req, |mut response: Response| {
assert_eq!(response.status(), Status::Ok); assert_eq!(response.status(), Status::Ok);
let body = response.body().unwrap().into_string().unwrap(); let body = response.body().unwrap().into_string().unwrap();
assert!(!body.contains("Hello, world!")); assert!(!body.contains("Hello, world!"));