The backend of a gist server written in Rust
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

snippet.rs 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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::snippets;
  8. #[derive(Queryable, Serialize, Deserialize)]
  9. pub struct Snippet {
  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 = "snippets"]
  19. pub struct InsertableSnippet {
  20. pub title: String,
  21. pub body: String,
  22. pub filetype: Option<String>,
  23. pub formatted_body: String,
  24. }
  25. fn format_snippet(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 get(connection: &PGC, id: i32) -> QueryResult<Snippet> {
  41. snippets::table.find(id).get_result::<Snippet>(connection)
  42. }
  43. pub fn insert(snippet: InsertableSnippet, connection: &PGC) -> QueryResult<Snippet> {
  44. let formatted_snippet = InsertableSnippet {
  45. filetype: snippet.filetype.clone(),
  46. title: snippet.title,
  47. body: snippet.body.clone(),
  48. formatted_body: format_snippet(snippet.filetype, snippet.body),
  49. };
  50. diesel::insert_into(snippets::table)
  51. .values(formatted_snippet)
  52. .get_result(connection)
  53. }