Slight improvement of the api
This commit is contained in:
parent
cf607ae345
commit
db0783fe2e
3 changed files with 12 additions and 26 deletions
|
@ -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<Post> {
|
||||
|
|
|
@ -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<ServerState>) -> Result<impl Responder> {
|
||||
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")]
|
||||
|
|
|
@ -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(())
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue