1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- 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 syntect::highlighting::ThemeSet;
- use syntect::html::highlighted_html_for_string;
- use syntect::parsing::SyntaxSet;
-
- 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(connection: DbConn) -> Result<Json<Vec<Gist>>, Status> {
- gists::all(&connection)
- .map(|gists| Json(gists))
- .map_err(|error| error_response(error))
- }
-
- #[get("/gists/<id>")]
- pub fn show_gist(id: i32, connection: DbConn) -> Template {
- let gist = match gists::get(&connection, id) {
- Ok(gist) => Some(gist),
- Err(_) => None,
- };
- let mut context = HashMap::new();
-
- match gist {
- Some(g) => {
- let body = match g.filetype {
- Some(filetype) => {
- let ps = SyntaxSet::load_defaults_newlines();
- let ts = ThemeSet::load_defaults();
- let syntax = ps.find_syntax_by_extension(&filetype);
-
- match syntax {
- Some(s) => highlighted_html_for_string(
- &g.body,
- &ps,
- s,
- &ts.themes["Solarized (light)"],
- ),
- None => format!("<pre class='plaintext'>{}</pre>", g.body),
- }
- }
- None => format!("<pre class='plaintext'>{}</pre>", g.body),
- };
- context.insert("title", g.title.clone());
- context.insert("body", body);
- }
- None => {
- context.insert("title", "404".to_string());
- context.insert("body", "<h3>Gist not found</h3>".to_string());
- }
- }
-
- 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))
- }
|