Rocket/examples/todo/src/main.rs

76 lines
2.2 KiB
Rust
Raw Normal View History

#![feature(plugin, custom_derive, custom_attribute)]
2016-09-09 03:38:58 +00:00
#![plugin(rocket_codegen, serde_macros, diesel_codegen)]
extern crate rocket;
#[macro_use] extern crate diesel;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate rocket_contrib;
extern crate serde_json;
mod static_files;
mod task;
use rocket::Rocket;
use rocket::response::{Flash, Redirect};
use rocket_contrib::Template;
use task::Task;
#[derive(Debug, Serialize)]
struct Context<'a, 'b>{msg: Option<(&'a str, &'b str)>, tasks: Vec<Task>}
impl<'a, 'b> Context<'a, 'b> {
pub fn err(msg: &'a str) -> Context<'static, 'a> {
Context{msg: Some(("error", msg)), tasks: Task::all()}
}
pub fn raw(msg: Option<(&'a str, &'b str)>) -> Context<'a, 'b> {
Context{msg: msg, tasks: Task::all()}
}
}
2016-09-04 11:06:28 +00:00
#[post("/", form = "<todo>")]
fn new(todo: Task) -> Result<Flash<Redirect>, Template> {
if todo.description.is_empty() {
2016-09-30 04:41:21 +00:00
Err(Template::render("index", &Context::err("Description cannot be empty.")))
} else if todo.insert() {
Ok(Flash::success(Redirect::to("/"), "Todo successfully added."))
} else {
2016-09-30 04:41:21 +00:00
Err(Template::render("index", &Context::err("Whoops! The server failed.")))
}
}
// Should likely do something to simulate PUT.
#[put("/<id>")]
fn toggle(id: i32) -> Result<Redirect, Template> {
if Task::toggle_with_id(id) {
Ok(Redirect::to("/"))
} else {
2016-09-30 04:41:21 +00:00
Err(Template::render("index", &Context::err("Couldn't toggle task.")))
}
}
// Should likely do something to simulate DELETE.
#[delete("/<id>")]
fn delete(id: i32) -> Result<Flash<Redirect>, Template> {
if Task::delete_with_id(id) {
Ok(Flash::success(Redirect::to("/"), "Todo was deleted."))
} else {
2016-09-30 04:41:21 +00:00
Err(Template::render("index", &Context::err("Couldn't delete task.")))
}
}
2016-09-04 11:06:28 +00:00
#[get("/")]
fn index(msg: Option<Flash<()>>) -> Template {
2016-09-30 04:41:21 +00:00
Template::render("index", &match msg {
Some(ref msg) => Context::raw(Some((msg.name(), msg.msg()))),
None => Context::raw(None),
})
}
fn main() {
let mut rocket = Rocket::new("127.0.0.1", 8000);
rocket.mount("/", routes![index, static_files::all])
.mount("/todo/", routes![new, toggle, delete]);
rocket.launch();
}