From ec2322f04cc7d1acbfb78a3dcdc28636c0af99ee Mon Sep 17 00:00:00 2001 From: linlkin Date: Fri, 6 Dec 2024 03:52:12 +0100 Subject: [PATCH] better api and yyyy/mm/dd format for dates in the db --- back/src/create_db.rs | 4 ++- back/src/main.rs | 67 +++++++++++++++++++++++++++++++++++++------ 2 files changed, 61 insertions(+), 10 deletions(-) diff --git a/back/src/create_db.rs b/back/src/create_db.rs index 67eb2af..21cb84a 100644 --- a/back/src/create_db.rs +++ b/back/src/create_db.rs @@ -12,7 +12,9 @@ pub fn init() -> sqlite::Result<()> { "CREATE TABLE IF NOT EXISTS articles ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, - subTitle TEXT, + auteur TEXT, + edited_at DATE_FORMAT('now', '%YYYY-%mm-%dd'), + published_at DATE_FORMAT('now', '%YYYY-%mm-%dd'), content TEXT NOT NULL )", )?; diff --git a/back/src/main.rs b/back/src/main.rs index ad8f7f5..141544d 100644 --- a/back/src/main.rs +++ b/back/src/main.rs @@ -1,7 +1,7 @@ mod create_db; use create_db::init; -use actix_web::{App, HttpServer, get, Responder, HttpResponse, http::header::ContentType}; +use actix_web::{App, web, HttpServer, get, Responder, HttpResponse, http::header::ContentType}; use actix_files::Files; use serde_json::json; use sqlite::{Connection, State}; @@ -11,9 +11,9 @@ use serde::{Serialize, Deserialize}; struct Article { id: i64, title: String, - auteur: Option, - edited_at: Option, - published_at: Option, + auteur: String, + edited_at: String, + published_at: String, content: String, } @@ -31,13 +31,13 @@ async fn get_articles() -> impl Responder { while let State::Row = stmt.next().unwrap() { let id = stmt.read::(0).unwrap(); let title = stmt.read::(1).unwrap(); - let content = stmt.read::(3).unwrap(); + let content = stmt.read::(5).unwrap(); articles.push(Article { id, title, - auteur: None, - edited_at: None, - published_at: None, + auteur: "".to_string(), + edited_at: "".to_string(), + published_at: "".to_string(), content }); } @@ -45,6 +45,54 @@ async fn get_articles() -> impl Responder { HttpResponse::Ok().json(articles) } + +#[get("/api/articles/{id}")] +async fn get_article(path: web::Path) -> impl Responder { + let id = path.into_inner(); + + // Open the database connection + let conn = match Connection::open("./data/data.db") { + Ok(conn) => conn, + Err(err) => { + eprintln!("Failed to connect to database: {}", err); + return HttpResponse::InternalServerError().body("Failed to connect to database"); + } + }; + + // Fetch the article from the database + match fetch_article_by_id(&conn, id) { + Ok(Some(article)) => HttpResponse::Ok().json(article), + Ok(None) => HttpResponse::NotFound().body(format!("Article with ID {} not found", id)), + Err(err) => { + eprintln!("Database query error: {}", err); + HttpResponse::InternalServerError().body("Database query failed") + } + } +} + +/// Fetches an article by its ID from the database. +fn fetch_article_by_id(conn: &Connection, id: i64) -> Result, sqlite::Error> { + let mut stmt = conn.prepare( + "SELECT id, title, auteur, edited_at, published_at, content + FROM articles WHERE id = ?1" + )?; + stmt.bind((1, id))?; + + let mut article = None; + while let State::Row = stmt.next()? { + article = Some(Article { + id: stmt.read::(0)?, + title: stmt.read::(1)?, + auteur: stmt.read::(2)?, + edited_at: stmt.read::(3)?, + published_at: stmt.read::(4)?, + content: stmt.read::(5)?, + }); + } + + Ok(article) +} + #[get("/api")] async fn api() -> impl Responder { let value = json!({ @@ -72,9 +120,10 @@ async fn main() -> Result<(), std::io::Error> { .service(hello) .service(get_articles) .service(api) + .service(get_article) .service(Files::new("/", "public").index_file("index.html")) }) - .bind(("0.0.0.0", 8080))? + .bind(("0.0.0.0", 2486))? .run() .await }