12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- use diesel::result::Error;
- use rocket::http::Status;
- use rocket::request::Request;
- use rocket::response::status;
- use rocket_contrib::json::Json;
- use rocket_contrib::templates::Template;
- use std::collections::HashMap;
-
- use crate::connection::DbConn;
- use crate::snippet;
- use crate::snippet::{InsertableSnippet, Snippet};
-
- 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("/snippets/<id>")]
- pub fn show_snippet(id: i32, connection: DbConn) -> Template {
- let mut context: HashMap<&str, Snippet> = HashMap::new();
- if let Ok(snippet) = snippet::get(&connection, id) {
- context.insert("snippet", snippet);
- }
-
- Template::render("snippets/show", &context)
- }
-
- #[get("/snippets/<id>/raw")]
- pub fn show_raw_snippet(id: i32, connection: DbConn) -> String {
- match snippet::get(&connection, id) {
- Ok(snippet) => snippet.body,
- Err(_) => String::from("Snippet not found"),
- }
- }
-
- #[post("/api/snippets", format = "application/json", data = "<snippet>")]
- pub fn create_snippet(
- snippet: Json<InsertableSnippet>,
- connection: DbConn,
- ) -> Result<status::Created<Json<Snippet>>, Status> {
- snippet::insert(snippet.into_inner(), &connection)
- .map(|snippet| status::Created(String::from(""), Some(Json(snippet))))
- .map_err(error_response)
- }
-
- #[catch(400)]
- pub fn bad_request(req: &Request) -> String {
- req.headers().get_one("content-length").map_or(
- String::from("{\"message\": \"Bad request\"}"),
- |length| {
- if length
- .parse::<i32>()
- .expect("Content length is non-numeric")
- > 1_000_000
- {
- String::from("{\"message\": \"Snippet must be under 1mb\"}")
- } else {
- String::from("{\"message\": \"Bad request\"}")
- }
- },
- )
- }
|