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.

mod.rs 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. use chrono::NaiveDateTime;
  2. use diesel::pg::PgConnection as PGC;
  3. use diesel::prelude::*;
  4. use syntect::highlighting::ThemeSet;
  5. use syntect::html::highlighted_html_for_string;
  6. use syntect::parsing::SyntaxSet;
  7. use crate::schema::gists;
  8. #[derive(Queryable, Serialize, Deserialize)]
  9. pub struct Gist {
  10. pub id: i32,
  11. pub title: String,
  12. pub body: String,
  13. pub created_at: Option<NaiveDateTime>,
  14. pub filetype: Option<String>,
  15. pub formatted_body: String,
  16. }
  17. #[derive(Insertable, AsChangeset, Serialize, Deserialize)]
  18. #[table_name = "gists"]
  19. pub struct InsertableGist {
  20. pub title: String,
  21. pub body: String,
  22. pub filetype: Option<String>,
  23. pub formatted_body: String,
  24. }
  25. fn format_gist(filetype: Option<String>, body: String) -> String {
  26. filetype.map_or(
  27. format!("<pre class='plaintext'>{}</pre>", body),
  28. |filetype| {
  29. let ps = SyntaxSet::load_defaults_newlines();
  30. let ts = ThemeSet::load_defaults();
  31. ps.find_syntax_by_extension(&filetype).map_or(
  32. format!("<pre class='plaintext'>{}</pre>", body),
  33. |syntax| {
  34. highlighted_html_for_string(&body, &ps, syntax, &ts.themes["Solarized (light)"])
  35. },
  36. )
  37. },
  38. )
  39. }
  40. pub fn all(connection: &PGC) -> QueryResult<Vec<Gist>> {
  41. gists::table.load::<Gist>(&*connection)
  42. }
  43. pub fn get(connection: &PGC, id: i32) -> QueryResult<Gist> {
  44. gists::table.find(id).get_result::<Gist>(connection)
  45. }
  46. pub fn insert(gist: InsertableGist, connection: &PGC) -> QueryResult<Gist> {
  47. let formatted_gist = InsertableGist {
  48. filetype: gist.filetype.clone(),
  49. title: gist.title,
  50. body: gist.body.clone(),
  51. formatted_body: format_gist(gist.filetype, gist.body),
  52. };
  53. diesel::insert_into(gists::table)
  54. .values(formatted_gist)
  55. .get_result(connection)
  56. }