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_json = "0.9"
serde_derive = "0.9"
lazy_static = "*"
[dependencies.rocket_contrib]
path = "../../contrib"

View File

@ -3,13 +3,13 @@
extern crate rocket;
extern crate serde_json;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate serde_derive;
#[cfg(test)] mod tests;
use rocket_contrib::{JSON, Value};
use rocket::State;
use std::collections::HashMap;
use std::sync::Mutex;
@ -17,9 +17,7 @@ use std::sync::Mutex;
type ID = usize;
// We're going to store all of the messages here. No need for a DB.
lazy_static! {
static ref MAP: Mutex<HashMap<ID, String>> = Mutex::new(HashMap::new());
}
type MessageMap = Mutex<HashMap<ID, String>>;
#[derive(Serialize, Deserialize)]
struct Message {
@ -29,8 +27,8 @@ struct Message {
// TODO: This example can be improved by using `route` with muliple HTTP verbs.
#[post("/<id>", format = "application/json", data = "<message>")]
fn new(id: ID, message: JSON<Message>) -> JSON<Value> {
let mut hashmap = MAP.lock().expect("map lock.");
fn new(id: ID, message: JSON<Message>, map: State<MessageMap>) -> JSON<Value> {
let mut hashmap = map.lock().expect("map lock.");
if hashmap.contains_key(&id) {
JSON(json!({
"status": "error",
@ -43,8 +41,8 @@ fn new(id: ID, message: JSON<Message>) -> JSON<Value> {
}
#[put("/<id>", format = "application/json", data = "<message>")]
fn update(id: ID, message: JSON<Message>) -> Option<JSON<Value>> {
let mut hashmap = MAP.lock().unwrap();
fn update(id: ID, message: JSON<Message>, map: State<MessageMap>) -> Option<JSON<Value>> {
let mut hashmap = map.lock().unwrap();
if hashmap.contains_key(&id) {
hashmap.insert(id, message.0.contents);
Some(JSON(json!({ "status": "ok" })))
@ -54,8 +52,8 @@ fn update(id: ID, message: JSON<Message>) -> Option<JSON<Value>> {
}
#[get("/<id>", format = "application/json")]
fn get(id: ID) -> Option<JSON<Message>> {
let hashmap = MAP.lock().unwrap();
fn get(id: ID, map: State<MessageMap>) -> Option<JSON<Message>> {
let hashmap = map.lock().unwrap();
hashmap.get(&id).map(|contents| {
JSON(Message {
id: Some(id),
@ -72,9 +70,13 @@ fn not_found() -> JSON<Value> {
}))
}
fn main() {
fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/message", routes![new, update, get])
.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;
macro_rules! run_test {
($req:expr, $test_fn:expr) => ({
let rocket = rocket::ignite()
.mount("/message", routes![super::new, super::update, super::get])
.catch(errors![super::not_found]);
($rocket: expr, $req:expr, $test_fn:expr) => ({
let mut req = $req;
$test_fn(req.dispatch_with(&rocket));
$test_fn(req.dispatch_with($rocket));
})
}
#[test]
fn bad_get_put() {
let rocket = rocket();
// Try to get a message with an ID that doesn't exist.
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);
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.
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);
let body = response.body().unwrap().into_string().unwrap();
assert!(body.contains("error"));
@ -37,7 +35,7 @@ fn bad_get_put() {
// Try to put a message without a proper body.
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);
});
@ -46,16 +44,17 @@ fn bad_get_put() {
.header(ContentType::JSON)
.body(r#"{ "contents": "Bye bye, world!" }"#);
run_test!(req, |response: Response| {
run_test!(&rocket, req, |response: Response| {
assert_eq!(response.status(), Status::NotFound);
});
}
#[test]
fn post_get_put_get() {
let rocket = rocket();
// Check that a message with ID 1 doesn't exist.
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);
});
@ -64,13 +63,13 @@ fn post_get_put_get() {
.header(ContentType::JSON)
.body(r#"{ "contents": "Hello, world!" }"#);
run_test!(req, |response: Response| {
run_test!(&rocket, req, |response: Response| {
assert_eq!(response.status(), Status::Ok);
});
// Check that the message exists with the correct contents.
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);
let body = response.body().unwrap().into_string().unwrap();
assert!(body.contains("Hello, world!"));
@ -81,13 +80,13 @@ fn post_get_put_get() {
.header(ContentType::JSON)
.body(r#"{ "contents": "Bye bye, world!" }"#);
run_test!(req, |response: Response| {
run_test!(&rocket, req, |response: Response| {
assert_eq!(response.status(), Status::Ok);
});
// Check that the message exists with the updated contents.
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);
let body = response.body().unwrap().into_string().unwrap();
assert!(!body.contains("Hello, world!"));