FrostByte/server/src/db.rs
2023-10-21 00:59:35 +02:00

36 lines
863 B
Rust

use crate::routes::{NewPost, Post};
use log::warn;
use sqlx::SqlitePool;
// Gets all posts from the database
pub async fn db_get_posts(pool: &SqlitePool) -> Vec<Post> {
sqlx::query_as!(Post, "SELECT * FROM posts")
.fetch_all(pool)
.await
.unwrap()
}
// 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;
}
let q = sqlx::query_as!(
Post,
"SELECT * FROM posts WHERE id = (SELECT MAX(id) FROM posts)"
)
.fetch_one(pool)
.await
.ok()?;
Some(q)
}