FrostByte/server/src/db.rs

42 lines
1,008 B
Rust
Raw Normal View History

2023-10-20 20:57:58 +02:00
use crate::routes::{NewPost, Post};
use log::warn;
2023-10-21 00:59:35 +02:00
use sqlx::SqlitePool;
2023-10-20 06:06:55 +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> {
let q2 = sqlx::query!(
"INSERT INTO posts (user_id, content) VALUES (1, ?)",
post.content
)
.execute(pool)
.await;
if q2.is_err() {
let s = q2.err().unwrap();
warn!("Error inserting post into database: {}", s);
return None;
}
2023-10-20 06:06:55 +02:00
2023-10-20 20:57:58 +02:00
let q = sqlx::query_as!(
Post,
"SELECT * FROM posts WHERE id = (SELECT MAX(id) FROM posts)"
)
.fetch_one(pool)
.await
.ok()?;
Some(q)
2023-10-20 06:06:55 +02:00
}