2023-10-20 20:57:58 +02:00
|
|
|
use crate::routes::{NewPost, Post};
|
2023-10-20 22:49:09 +02:00
|
|
|
use log::warn;
|
2023-10-21 00:59:35 +02:00
|
|
|
use sqlx::SqlitePool;
|
2023-10-20 06:06:55 +02:00
|
|
|
|
2023-10-21 01:55:27 +02:00
|
|
|
// Gets the latest posts from the database, ordered by created_at
|
|
|
|
pub async fn db_get_latest_posts(pool: &SqlitePool, limit: i64, offset: i64) -> Vec<Post> {
|
|
|
|
sqlx::query_as!(
|
|
|
|
Post,
|
|
|
|
"SELECT * FROM posts ORDER BY created_at DESC LIMIT ? OFFSET ?",
|
|
|
|
limit,
|
|
|
|
offset
|
|
|
|
)
|
|
|
|
.fetch_all(pool)
|
|
|
|
.await
|
|
|
|
.unwrap()
|
2023-10-20 06:06:55 +02:00
|
|
|
}
|
|
|
|
|
2023-10-20 20:57:58 +02:00
|
|
|
// Inserts a new post to the database
|
|
|
|
pub async fn db_new_post(post: NewPost, pool: &SqlitePool) -> Option<Post> {
|
2023-10-21 05:11:42 +02:00
|
|
|
let insert_query = sqlx::query!(
|
2023-10-20 22:49:09 +02:00
|
|
|
"INSERT INTO posts (user_id, content) VALUES (1, ?)",
|
|
|
|
post.content
|
|
|
|
)
|
|
|
|
.execute(pool)
|
|
|
|
.await;
|
|
|
|
|
2023-10-21 05:11:42 +02:00
|
|
|
if insert_query.is_err() {
|
|
|
|
let s = insert_query.err().unwrap();
|
2023-10-20 22:49:09 +02:00
|
|
|
warn!("Error inserting post into database: {}", s);
|
|
|
|
return None;
|
|
|
|
}
|
2023-10-20 06:06:55 +02:00
|
|
|
|
2023-10-21 05:11:42 +02:00
|
|
|
// Dips into the database to get the post we just inserted
|
|
|
|
let post = sqlx::query_as!(
|
2023-10-20 20:57:58 +02:00
|
|
|
Post,
|
|
|
|
"SELECT * FROM posts WHERE id = (SELECT MAX(id) FROM posts)"
|
|
|
|
)
|
|
|
|
.fetch_one(pool)
|
|
|
|
.await
|
|
|
|
.ok()?;
|
2023-10-21 05:11:42 +02:00
|
|
|
|
|
|
|
Some(post)
|
2023-10-20 06:06:55 +02:00
|
|
|
}
|