From db0783fe2e4ead50f5a6a66e79ce8406f644d246 Mon Sep 17 00:00:00 2001 From: Imbus Date: Sat, 21 Oct 2023 00:59:35 +0200 Subject: [PATCH] Slight improvement of the api --- server/src/db.rs | 2 +- server/src/routes/post.rs | 7 ++----- server/src/state.rs | 29 +++++++++-------------------- 3 files changed, 12 insertions(+), 26 deletions(-) diff --git a/server/src/db.rs b/server/src/db.rs index c2f0f39..65b74f4 100644 --- a/server/src/db.rs +++ b/server/src/db.rs @@ -1,6 +1,6 @@ use crate::routes::{NewPost, Post}; use log::warn; -use sqlx::{Row, SqlitePool}; +use sqlx::SqlitePool; // Gets all posts from the database pub async fn db_get_posts(pool: &SqlitePool) -> Vec { diff --git a/server/src/routes/post.rs b/server/src/routes/post.rs index cc7970c..0555e47 100755 --- a/server/src/routes/post.rs +++ b/server/src/routes/post.rs @@ -1,4 +1,4 @@ -use crate::db::db_new_post; +use crate::db::{db_get_posts, db_new_post}; use crate::ServerState; use actix_web::web::Data; @@ -38,10 +38,7 @@ pub struct User { #[get("/posts")] pub async fn get_posts(state: Data) -> Result { - let stream = sqlx::query_as!(Post, "SELECT * FROM posts"); - - let posts = stream.fetch_all(&state.pool).await.unwrap(); - Ok(HttpResponse::Ok().json(posts)) + Ok(HttpResponse::Ok().json(db_get_posts(&state.pool).await)) } #[post("/posts")] diff --git a/server/src/state.rs b/server/src/state.rs index 783b08d..fbda6c8 100644 --- a/server/src/state.rs +++ b/server/src/state.rs @@ -23,7 +23,7 @@ impl ServerState { sqlx::migrate!("./migrations").run(&pool).await.unwrap(); #[cfg(debug_assertions)] - debug_setup(&pool).await; + debug_setup(&pool).await.unwrap(); Self { pool } } @@ -32,27 +32,16 @@ impl ServerState { // Inserts a bunch of dummy data into the database // Mostly useful for debugging new posts, as we need to satisfy foreign key constraints. #[cfg(debug_assertions)] -async fn debug_setup(pool: &SqlitePool) { - use chrono::NaiveDateTime; +async fn debug_setup(pool: &SqlitePool) -> Result<(), sqlx::Error> { use sqlx::query; - let now = NaiveDateTime::from_timestamp(0, 0); + query!("INSERT INTO users (username, password) VALUES ('testuser', 'testpassword')",) + .execute(pool) + .await?; - query!( - "INSERT INTO users (username, password, created_at, updated_at) VALUES ('test', 'test', ?, ?)", - now, - now - ) - .execute(pool) - .await - .unwrap(); + query!("INSERT INTO posts (user_id, content) VALUES (1, 'Hello world!')",) + .execute(pool) + .await?; - query!( - "INSERT INTO posts (user_id, content, created_at, updated_at) VALUES (1, 'Hello world!', ?, ?)", - now, - now - ) - .execute(pool) - .await - .unwrap(); + Ok(()) }