1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- use chrono::NaiveDateTime;
- use diesel::pg::PgConnection as PGC;
- use diesel::prelude::*;
- use syntect::highlighting::ThemeSet;
- use syntect::html::highlighted_html_for_string;
- use syntect::parsing::SyntaxSet;
-
- use crate::schema::gists;
-
- #[derive(Queryable, Serialize, Deserialize)]
- pub struct Gist {
- pub id: i32,
- pub title: String,
- pub body: String,
- pub created_at: Option<NaiveDateTime>,
- pub filetype: Option<String>,
- pub formatted_body: String,
- }
-
- #[derive(Insertable, AsChangeset, Serialize, Deserialize)]
- #[table_name = "gists"]
- pub struct InsertableGist {
- pub title: String,
- pub body: String,
- pub filetype: Option<String>,
- pub formatted_body: String,
- }
-
- fn format_gist(filetype: Option<String>, body: String) -> String {
- filetype.map_or(
- format!("<pre class='plaintext'>{}</pre>", body),
- |filetype| {
- let ps = SyntaxSet::load_defaults_newlines();
- let ts = ThemeSet::load_defaults();
- ps.find_syntax_by_extension(&filetype).map_or(
- format!("<pre class='plaintext'>{}</pre>", body),
- |syntax| {
- highlighted_html_for_string(&body, &ps, syntax, &ts.themes["Solarized (light)"])
- },
- )
- },
- )
- }
-
- pub fn get(connection: &PGC, id: i32) -> QueryResult<Gist> {
- gists::table.find(id).get_result::<Gist>(connection)
- }
-
- pub fn insert(gist: InsertableGist, connection: &PGC) -> QueryResult<Gist> {
- let formatted_gist = InsertableGist {
- filetype: gist.filetype.clone(),
- title: gist.title,
- body: gist.body.clone(),
- formatted_body: format_gist(gist.filetype, gist.body),
- };
- diesel::insert_into(gists::table)
- .values(formatted_gist)
- .get_result(connection)
- }
|