The backend of a gist server written in Rust
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

routes.rs 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use diesel::result::Error;
  2. use rocket::http::Status;
  3. use rocket::response::status;
  4. use rocket_contrib::json::Json;
  5. use rocket_contrib::templates::Template;
  6. use std::collections::HashMap;
  7. use crate::connection::DbConn;
  8. use crate::snippet;
  9. use crate::snippet::{InsertableSnippet, Snippet};
  10. fn error_response(error: Error) -> Status {
  11. match error {
  12. Error::NotFound => Status::NotFound,
  13. _ => Status::InternalServerError,
  14. }
  15. }
  16. #[get("/")]
  17. pub fn index() -> Template {
  18. let context: HashMap<&str, String> = HashMap::new();
  19. Template::render("index", &context)
  20. }
  21. #[get("/snippets/<id>")]
  22. pub fn show_snippet(id: i32, connection: DbConn) -> Template {
  23. let result = match snippet::get(&connection, id) {
  24. Ok(snippet) => Some(snippet),
  25. Err(_) => None,
  26. };
  27. let (title, body) = result.map_or(
  28. (
  29. String::from("404 - Snippet not found"),
  30. format!("<h3'>{}</h3>", "Snippet not found"),
  31. ),
  32. |snippet| (snippet.title, snippet.formatted_body),
  33. );
  34. let mut context: HashMap<&str, String> = HashMap::new();
  35. context.insert("title", title);
  36. context.insert("body", body);
  37. Template::render("snippets/show", &context)
  38. }
  39. #[post("/api/snippets", format = "application/json", data = "<snippet>")]
  40. pub fn create_snippet<'a>(
  41. snippet: Json<InsertableSnippet>,
  42. connection: DbConn,
  43. ) -> Result<status::Created<Json<Snippet>>, Status> {
  44. snippet::insert(snippet.into_inner(), &connection)
  45. .map(|snippet| status::Created(String::from(""), Some(Json(snippet))))
  46. .map_err(error_response)
  47. }