From 57d574d143c314e3b7eaf8c3043ad278b45e6605 Mon Sep 17 00:00:00 2001 From: linlkin Date: Thu, 5 Dec 2024 23:19:15 +0100 Subject: [PATCH] i added db and articles end points --- back/Cargo.toml | 2 +- back/data/data.db | 0 back/src/creat_db.rs | 15 +++++++++++++++ back/src/main.rs | 29 +++++++++++++++++++++++++++-- 4 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 back/data/data.db create mode 100644 back/src/creat_db.rs diff --git a/back/Cargo.toml b/back/Cargo.toml index 8b48126..9a70ea3 100644 --- a/back/Cargo.toml +++ b/back/Cargo.toml @@ -6,4 +6,4 @@ edition = "2021" [dependencies] actix-files = "0.6.6" actix-web = "4" - +sqlite = "0.36.1" diff --git a/back/data/data.db b/back/data/data.db new file mode 100644 index 0000000..e69de29 diff --git a/back/src/creat_db.rs b/back/src/creat_db.rs new file mode 100644 index 0000000..ec5a2ed --- /dev/null +++ b/back/src/creat_db.rs @@ -0,0 +1,15 @@ +use sqlite::{Connection, State}; + +fn main() -> sqlite::Result<()> { + let conn = Connection::open("./data/data.db")?; + + conn.execute( + "CREATE TABLE articles ( + id INTEGER PRIMARY KEY, + title TEXT NOT NULL, + subTitle TEXT, + content TEXT NOT NULL, + )", + [], + )?; +} \ No newline at end of file diff --git a/back/src/main.rs b/back/src/main.rs index d4d0ee1..f0a5196 100644 --- a/back/src/main.rs +++ b/back/src/main.rs @@ -1,10 +1,14 @@ -use actix_web::{App, HttpServer}; +use actix_web::{get, http, post, web, App, HttpResponse, HttpServer, Responder}; use actix_files::Files; +use sqlite::{Connection, State, Error}; #[actix_web::main] -async fn main() -> std::io::Result<()> { +async fn main() -> Result<(), std::io::Error> { + let conn = Connection::open("./data/data.db"); + HttpServer::new(|| { App::new() + .service(hello) .service(Files::new("/", "./public").index_file("index.html")) }) .bind(("0.0.0.0", 8080))? @@ -12,3 +16,24 @@ async fn main() -> std::io::Result<()> { .await } +#[get("/api/hello")] +async fn hello() -> impl Responder { + HttpResponse::Ok().body("Hello world!") +} + +#[get("/api/articles")] +async fn get_articles() -> impl Responder { + let conn = Connection::open("./data/data.db").unwrap(); + let mut stmt = conn.prepare("SELECT * FROM articles").unwrap(); + let mut articles = Vec::new(); + + while let State::Row = stmt.next().unwrap() { + let id = stmt.read::(0).unwrap(); + let title = stmt.read::(1).unwrap(); + let subTitle = stmt.read::(2).unwrap(); + let content = stmt.read::(3).unwrap(); + articles.push((id, title, subTitle, content)); + } + + HttpResponse::Ok().json(articles) +} -- 2.47.2