From 0ea21cfaf3d35131b95ab25ad3c181c1befd016b Mon Sep 17 00:00:00 2001 From: Imbus Date: Fri, 20 Oct 2023 22:49:09 +0200 Subject: [PATCH] Changes related to api in both client and server --- client-solid/src/api.ts | 6 +++--- server/src/db.rs | 16 +++++++++++++--- server/src/main.rs | 1 + server/src/state.rs | 39 ++++++++++++++++++++++++++++++++++----- 4 files changed, 51 insertions(+), 11 deletions(-) diff --git a/client-solid/src/api.ts b/client-solid/src/api.ts index 70b9a6f..b1ed3a6 100644 --- a/client-solid/src/api.ts +++ b/client-solid/src/api.ts @@ -20,20 +20,20 @@ export interface Post extends NewPost { export async function getPosts(): Promise { // const res = await fetch(`${API_URL}/posts`); - const res = await fetch("/api/"); + const res = await fetch("/api/posts"); const data = await res.json(); return data; } export async function getPost(id: string): Promise { - const res = await fetch(`/api/${id}`); + const res = await fetch(`/api/posts/${id}`); const data = await res.json(); return data; } export async function createPost(post: NewPost): Promise { // await fetch(`${API_URL}`, { - await fetch("/api/", { + await fetch("/api/posts", { method: "POST", headers: { "Content-Type": "application/json", diff --git a/server/src/db.rs b/server/src/db.rs index 69b90e6..c2f0f39 100644 --- a/server/src/db.rs +++ b/server/src/db.rs @@ -1,4 +1,5 @@ use crate::routes::{NewPost, Post}; +use log::warn; use sqlx::{Row, SqlitePool}; // Gets all posts from the database @@ -11,9 +12,18 @@ pub async fn db_get_posts(pool: &SqlitePool) -> Vec { // Inserts a new post to the database pub async fn db_new_post(post: NewPost, pool: &SqlitePool) -> Option { - let q2 = sqlx::query!("INSERT INTO posts (content) VALUES (?)", post.content) - .execute(pool) - .await; + 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, diff --git a/server/src/main.rs b/server/src/main.rs index 9192906..18e07d2 100755 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -24,6 +24,7 @@ async fn main() -> std::io::Result<()> { App::new() .wrap(middleware::Compress::default()) .wrap(middleware::Logger::default()) + .wrap(middleware::NormalizePath::trim()) .service( scope("/api") .service(get_posts) diff --git a/server/src/state.rs b/server/src/state.rs index c1e0339..783b08d 100644 --- a/server/src/state.rs +++ b/server/src/state.rs @@ -1,5 +1,6 @@ use sqlx::Pool; use sqlx::Sqlite; +use sqlx::SqlitePool; use sqlx::{self, sqlite}; #[derive(Clone)] @@ -11,7 +12,7 @@ impl ServerState { pub async fn new() -> Self { // This is almost certainly bad practice for more reasons than I can count dotenvy::dotenv().ok(); - let db_url = dotenvy::var("DATABASE_URL").unwrap_or("sqlite:./db.sqlite".to_string()); + let db_url = dotenvy::var("DATABASE_URL").unwrap_or(":memory:".to_string()); let pool = sqlite::SqlitePoolOptions::new() .max_connections(5) @@ -21,9 +22,37 @@ impl ServerState { sqlx::migrate!("./migrations").run(&pool).await.unwrap(); - Self { - // posts: Arc::new(Mutex::new(BTreeMap::new())), - pool: pool, - } + #[cfg(debug_assertions)] + debug_setup(&pool).await; + + Self { pool } } } + +// 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; + use sqlx::query; + + let now = NaiveDateTime::from_timestamp(0, 0); + + 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, created_at, updated_at) VALUES (1, 'Hello world!', ?, ?)", + now, + now + ) + .execute(pool) + .await + .unwrap(); +}