12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- use diesel::result::Error;
- use rocket::http::Status;
- use rocket::response::status;
- use rocket_contrib::json::Json;
- use rocket_contrib::templates::Template;
- use std::collections::HashMap;
-
- use crate::connection::DbConn;
- use crate::gists;
- use crate::gists::{Gist, InsertableGist};
-
- fn error_response(error: Error) -> Status {
- match error {
- Error::NotFound => Status::NotFound,
- _ => Status::InternalServerError,
- }
- }
-
- #[get("/")]
- pub fn index() -> Template {
- let context: HashMap<&str, String> = HashMap::new();
- Template::render("index", &context)
- }
-
- #[get("/gists/<id>")]
- pub fn show_gist(id: i32, connection: DbConn) -> Template {
- let result = match gists::get(&connection, id) {
- Ok(gist) => Some(gist),
- Err(_) => None,
- };
-
- let (title, body) = result.map_or(
- (
- String::from("404 - Gist not found"),
- format!("<h3'>{}</h3>", "Gist not found"),
- ),
- |gist| (gist.title, gist.formatted_body),
- );
-
- let mut context: HashMap<&str, String> = HashMap::new();
- context.insert("title", title);
- context.insert("body", body);
-
- Template::render("gists/show", &context)
- }
-
- #[post("/api/gists", format = "application/json", data = "<gist>")]
- pub fn create_gist<'a>(
- gist: Json<InsertableGist>,
- connection: DbConn,
- ) -> Result<status::Created<Json<Gist>>, Status> {
- gists::insert(gist.into_inner(), &connection)
- .map(|gist| status::Created(String::from(""), Some(Json(gist))))
- .map_err(|error| error_response(error))
- }
|