From 4f09648a34a9bb91ba487ff5f345278ce2e66f46 Mon Sep 17 00:00:00 2001 From: Lumither Tao Date: Sat, 4 May 2024 21:06:01 +0800 Subject: [PATCH] feat(backend/api/get/post/) implement api --- backend/post.sql | 6 ++- backend/src/api/get/get_post.rs | 67 ++++++++++++++++++++++++++++++--- backend/tag.sql | 6 ++- 3 files changed, 72 insertions(+), 7 deletions(-) diff --git a/backend/post.sql b/backend/post.sql index 120e885..b27b701 100644 --- a/backend/post.sql +++ b/backend/post.sql @@ -17,4 +17,8 @@ ON CONFLICT (post_id) summary = excluded.summary, content = excluded.content, last_update = excluded.last_update, - first_update = excluded.first_update + first_update = excluded.first_update; + +SELECT * +FROM Post +WHERE post_id = $1; diff --git a/backend/src/api/get/get_post.rs b/backend/src/api/get/get_post.rs index c3b4526..4ea0991 100644 --- a/backend/src/api/get/get_post.rs +++ b/backend/src/api/get/get_post.rs @@ -1,12 +1,69 @@ +use std::str::FromStr; + use axum::extract::{Path, State}; use axum::Json; -use serde_json::Value; -use sqlx::PgPool; +use chrono::NaiveDateTime; +use serde_json::{json, Map, Value}; +use sqlx::{PgPool, query, Row}; +use uuid::Uuid; pub async fn get_post( - State(_db_connection): State, + State(db_connection): State, Path(post_id): Path, ) -> Result, Json> { - dbg!(&post_id); - todo!() + let meta = query( + r#" +SELECT * +FROM Post +WHERE post_id = $1; + "#, + ) + .bind(Uuid::from_str(post_id.as_str()).expect("Failed to parse UUID")) + .fetch_one(&db_connection) + .await + .expect("Failed to execute db query"); + + let tags = query( + r#" +SELECT tag FROM Tag WHERE post_id = $1; + "#, + ) + .bind(Uuid::from_str(post_id.as_str()).expect("Failed to parse UUID")) + .fetch_all(&db_connection) + .await + .expect("Failed to execute db query"); + + let mut res = Map::new(); + + res.insert( + "title".to_string(), + json!(meta.get::("title")), + ); + res.insert( + "summary".to_string(), + json!(meta.get::("summary")), + ); + res.insert( + "content".to_string(), + json!(meta.get::("content")), + ); + res.insert( + "last_update".to_string(), + json!(meta.get::("last_update")), + ); + res.insert( + "first_update".to_string(), + json!(meta.get::("first_update")), + ); + + let tags: Vec = tags + .iter() + .map(|tag| { + let tag: String = tag.get("tag"); + tag + }) + .collect(); + res.insert("tags".to_string(), Value::from(tags)); + + Ok(Json::from(Value::from(res))) } diff --git a/backend/tag.sql b/backend/tag.sql index be061aa..80699c4 100644 --- a/backend/tag.sql +++ b/backend/tag.sql @@ -5,4 +5,8 @@ CREATE TABLE IF NOT EXISTS Tag ); INSERT INTO Tag -VALUES ($1, $2); \ No newline at end of file +VALUES ($1, $2); + +SELECT * +FROM Tag +WHERE post_id = $1;