|
| 1 | +use actix_web::{http::header, post, get, web, App, HttpResponse, HttpServer, ResponseError}; |
| 2 | +use askama::Template; |
| 3 | +use thiserror::Error; |
| 4 | +use r2d2_sqlite::SqliteConnectionManager; |
| 5 | +use r2d2::Pool; |
| 6 | +use rusqlite::params; |
| 7 | +use serde::Deserialize; |
| 8 | + |
| 9 | +#[derive(Deserialize)] |
| 10 | +struct AddParams { |
| 11 | + text: String, |
| 12 | +} |
| 13 | + |
| 14 | +#[derive(Deserialize)] |
| 15 | +struct DeleteParams { |
| 16 | + id: u32, |
| 17 | +} |
| 18 | + |
| 19 | +#[derive(Debug)] |
| 20 | +struct TodoEntry { |
| 21 | + id: u32, |
| 22 | + text: String, |
| 23 | +} |
| 24 | + |
| 25 | +#[derive(Template)] |
| 26 | +#[template(path = "index.html")] |
| 27 | +struct IndexTemplate { |
| 28 | + entries: Vec<TodoEntry>, |
| 29 | +} |
| 30 | + |
| 31 | +#[derive(Error, Debug)] |
| 32 | +enum MyError { |
| 33 | + #[error("Failed to render HTML")] |
| 34 | + AskamaError(#[from] askama::Error), |
| 35 | + |
| 36 | + #[error("Failed to get connection")] |
| 37 | + ConnectionPoolError(#[from] r2d2::Error), |
| 38 | + |
| 39 | + #[error("Failed SQL execution")] |
| 40 | + SQLiteError(#[from] rusqlite::Error), |
| 41 | +} |
| 42 | + |
| 43 | +impl ResponseError for MyError {} |
| 44 | + |
| 45 | + |
| 46 | +#[get("/")] |
| 47 | +async fn index(db: web::Data<Pool<SqliteConnectionManager>>) -> Result<HttpResponse, MyError> { |
| 48 | + let conn = db.get()?; |
| 49 | + // SQL文を Prepared Statementに変換 |
| 50 | + let mut statement = conn.prepare("SELECT id, text FROM todo")?; |
| 51 | + |
| 52 | + // Prepared Statement となっている SQL文を実行し、結果をTodoEntryに変換する。 |
| 53 | + let rows = statement.query_map(params![], |row| { |
| 54 | + let id = row.get(0)?; |
| 55 | + let text = row.get(1)?; |
| 56 | + Ok(TodoEntry {id, text}) |
| 57 | + })?; |
| 58 | + let mut entries = Vec::new(); |
| 59 | + for row in rows { |
| 60 | + entries.push(row?); |
| 61 | + } |
| 62 | + |
| 63 | + let html = IndexTemplate { entries }; |
| 64 | + let response_body = html.render()?; |
| 65 | + Ok(HttpResponse::Ok() |
| 66 | + .content_type("text/html") |
| 67 | + .body(response_body)) |
| 68 | +} |
| 69 | + |
| 70 | +#[post("/add")] |
| 71 | +async fn add_todo( |
| 72 | + params: web::Form<AddParams>, |
| 73 | + db: web::Data<r2d2::Pool<SqliteConnectionManager>> |
| 74 | +) -> Result<HttpResponse, MyError> { |
| 75 | + let conn = db.get()?; |
| 76 | + conn.execute("INSERT INTO todo (text) VALUES (?)", &[¶ms.text])?; |
| 77 | + Ok(HttpResponse::SeeOther().header(header::LOCATION, "/").finish()) |
| 78 | +} |
| 79 | + |
| 80 | +#[post("/delete")] |
| 81 | +async fn delete_todo( |
| 82 | + params: web::Form<DeleteParams>, |
| 83 | + db: web::Data<r2d2::Pool<SqliteConnectionManager>> |
| 84 | +) -> Result<HttpResponse, MyError> { |
| 85 | + let conn = db.get()?; |
| 86 | + conn.execute("DELETE FROM todo WHERE id=?", [params.id])?; |
| 87 | + Ok(HttpResponse::SeeOther().header(header::LOCATION, "/").finish()) |
| 88 | +} |
| 89 | + |
| 90 | + |
| 91 | +#[actix_rt::main] |
| 92 | +async fn main() -> Result<(), actix_web::Error> { |
| 93 | + let manager = SqliteConnectionManager::file("todo.db"); |
| 94 | + let pool = Pool::new(manager).expect("Failed to initialize the connection pool."); |
| 95 | + let conn = pool |
| 96 | + .get() |
| 97 | + .expect("Failde to get the connection from the pool."); |
| 98 | + conn.execute( |
| 99 | + "CREATE TABLE IF NOT EXISTS todo ( |
| 100 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 101 | + text TEXT NOT NULL |
| 102 | + )", |
| 103 | + params![], |
| 104 | + ) |
| 105 | + .expect("Failed to create a table `todo`."); |
| 106 | + |
| 107 | + //ここでコネクションプールを渡す |
| 108 | + HttpServer::new(move || { |
| 109 | + App::new() |
| 110 | + .service(index) |
| 111 | + .service(add_todo) |
| 112 | + .service(delete_todo) |
| 113 | + .data(pool.clone()) |
| 114 | + }) |
| 115 | + .bind("0.0.0.0:8080")? |
| 116 | + .run() |
| 117 | + .await?; |
| 118 | + Ok(()) |
| 119 | +} |
0 commit comments