前回の続き
データベースに追加する処理と削除する処理を作成していきます。
まず、フォームのデータを取得するのにserdeクレートを使用します。
[package]
name = "todo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = { version = "4.1" }
actix-rt = { version = "2.7" }
thiserror = { version = "1.0" }
askama = { version = "0.11" }
rusqlite = { version = "0.28", features=["bundled"] }
r2d2 = { version = "0.8" }
r2d2_sqlite = { version = "0.21" }
serde = { version = "1.0", feature = ["derive"] }
次に追加、削除のパスを作成していきます。
まずは追加処理。
#[post("/add")]
async fn add_todo (
params: web::Form<AddParams>,
db: web::Data<r2d2::Pool<SqliteConnectionManager>>,
) -> Result<HttpResponse, MyError> {
let conn = db.get()?;
conn.execute("INSERT INTO todo (text) VALUES (?)", &[¶ms.text])?;
Ok(HttpResponse::SeeOther()
.header(header::LOCATION, "/")
.finish())
}
同じように削除処理。
#[post("/delete")]
async fn delete_todo(
params: web::Form<DeleteParams>,
db: web::Data<r2d2::Pool<SqliteConnectionManager>>,
) -> Result<HttpResponse, MyError> {
let conn = db.get()?;
conn.execute("DELETE FROM todo WHERE id=?", &[¶ms.id])?;
Ok(HttpResponse::SeeOther()
.header(header::LOCATION, "/")
.finish())
}
そして、追加・削除のパスをサーバに登録。
#[actix_rt::main]
async fn main() -> Result<(), actix_web::Error> {
let manager = SqliteConnectionManager::file("todo.db");
let pool = Pool::new(manager).expect("Failed to inithialize the connection pool.");
let conn = pool.get().expect("Failed to get the connection from the pool.");
conn.execute(
"CREATE TABLE IF NOT EXISTS todo (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL
)",
params![],
)
.expect("Failed to create a table 'todo'.");
HttpServer::new(move || {
App::new()
.service(index)
.service(add_todo)
.service(delete_todo)
.data(pool.clone())
})
.bind("0.0.0.0:8080")?
.run()
.await?;
Ok(())
}
「RUST勉強中、8/21の積み上げ」への1件のフィードバック