45 lines
1.2 KiB
Rust
45 lines
1.2 KiB
Rust
use mysql::prelude::Queryable;
|
|
use mysql::{params, Error as MysqlError};
|
|
use r2d2::{Error as R2D2Error, Pool};
|
|
use r2d2_mysql::MySqlConnectionManager;
|
|
use thiserror::Error;
|
|
|
|
#[derive(Error, Debug)]
|
|
pub enum PostRepositoryError {
|
|
#[error("mysql error: {0}")]
|
|
MySqlError(#[from] MysqlError),
|
|
|
|
#[error("Connection pool error: {0}")]
|
|
PoolError(#[from] R2D2Error),
|
|
}
|
|
|
|
pub struct PostRepository {
|
|
pool: Pool<MySqlConnectionManager>,
|
|
}
|
|
|
|
impl PostRepository {
|
|
pub fn new(pool: Pool<MySqlConnectionManager>) -> Self {
|
|
PostRepository { pool }
|
|
}
|
|
|
|
/**
|
|
* 新建帖子
|
|
*/
|
|
pub fn insert_post(
|
|
&self,
|
|
title: &str,
|
|
content: &str,
|
|
link: &str,
|
|
popularity: &str,
|
|
) -> Result<(), PostRepositoryError> {
|
|
let mut conn = self.pool.get().map_err(PostRepositoryError::PoolError)?;
|
|
let sql = "INSERT INTO posts (title, content, link, popularity) VALUES (:title, :content, :link, :popularity)";
|
|
conn.exec_drop(
|
|
sql,
|
|
params! {"title" => title, "content" => content, "link" => link, "popularity" => popularity},
|
|
)
|
|
.map_err(PostRepositoryError::MySqlError)?;
|
|
Ok(())
|
|
}
|
|
}
|