i added db and articles end points #1

Merged
lucien merged 2 commits from back_end into main 2024-12-05 22:42:29 +00:00
4 changed files with 43 additions and 3 deletions

View file

@ -6,4 +6,4 @@ edition = "2021"
[dependencies]
actix-files = "0.6.6"
actix-web = "4"
sqlite = "0.36.1"

0
back/data/data.db Normal file
View file

15
back/src/creat_db.rs Normal file
View file

@ -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,
)",
[],
)?;
}

View file

@ -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::<i64, _>(0).unwrap();
let title = stmt.read::<String, _>(1).unwrap();
let subTitle = stmt.read::<String, _>(2).unwrap();
let content = stmt.read::<String, _>(3).unwrap();
articles.push((id, title, subTitle, content));
}
HttpResponse::Ok().json(articles)
}