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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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::gists;
  9. use crate::gists::{Gist, InsertableGist};
  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(connection: DbConn) -> Result<Json<Vec<Gist>>, Status> {
  18. gists::all(&connection)
  19. .map(|gists| Json(gists))
  20. .map_err(|error| error_response(error))
  21. }
  22. #[get("/gists/<id>")]
  23. pub fn show_gist(id: i32, connection: DbConn) -> Template {
  24. let result = match gists::get(&connection, id) {
  25. Ok(gist) => Some(gist),
  26. Err(_) => None,
  27. };
  28. let (title, body) = result.map_or(
  29. (
  30. String::from("404 - Gist not found"),
  31. format!("<h3'>{}</h3>", "Gist not found"),
  32. ),
  33. |gist| (gist.title, gist.formatted_body),
  34. );
  35. let mut context: HashMap<&str, String> = HashMap::new();
  36. context.insert("title", title);
  37. context.insert("body", body);
  38. Template::render("gists/show", &context)
  39. }
  40. #[post("/api/gists", format = "application/json", data = "<gist>")]
  41. pub fn create_gist<'a>(
  42. gist: Json<InsertableGist>,
  43. connection: DbConn,
  44. ) -> Result<status::Created<Json<Gist>>, Status> {
  45. gists::insert(gist.into_inner(), &connection)
  46. .map(|gist| status::Created(String::from(""), Some(Json(gist))))
  47. .map_err(|error| error_response(error))
  48. }