mirror of
https://github.com/actix/examples
synced 2025-06-27 01:27:43 +02:00
use sqlite in basics/todo
This commit is contained in:
@ -1,9 +1,10 @@
|
||||
use actix_files::NamedFile;
|
||||
use actix_session::Session;
|
||||
use actix_web::middleware::ErrorHandlerResponse;
|
||||
use actix_web::{dev, error, http, web, Error, HttpResponse, Result};
|
||||
use actix_web::{
|
||||
dev, error, http, middleware::ErrorHandlerResponse, web, Error, HttpResponse, Result,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use sqlx::postgres::PgPool;
|
||||
use sqlx::SqlitePool;
|
||||
use tera::{Context, Tera};
|
||||
|
||||
use crate::{
|
||||
@ -12,7 +13,7 @@ use crate::{
|
||||
};
|
||||
|
||||
pub async fn index(
|
||||
pool: web::Data<PgPool>,
|
||||
pool: web::Data<SqlitePool>,
|
||||
tmpl: web::Data<Tera>,
|
||||
session: Session,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
@ -44,7 +45,7 @@ pub struct CreateForm {
|
||||
|
||||
pub async fn create(
|
||||
params: web::Form<CreateForm>,
|
||||
pool: web::Data<PgPool>,
|
||||
pool: web::Data<SqlitePool>,
|
||||
session: Session,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
if params.description.is_empty() {
|
||||
@ -73,7 +74,7 @@ pub struct UpdateForm {
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
db: web::Data<PgPool>,
|
||||
db: web::Data<SqlitePool>,
|
||||
params: web::Path<UpdateParams>,
|
||||
form: web::Form<UpdateForm>,
|
||||
session: Session,
|
||||
@ -89,7 +90,7 @@ pub async fn update(
|
||||
}
|
||||
|
||||
async fn toggle(
|
||||
pool: web::Data<PgPool>,
|
||||
pool: web::Data<SqlitePool>,
|
||||
params: web::Path<UpdateParams>,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
db::toggle_task(params.id, &pool)
|
||||
@ -99,7 +100,7 @@ async fn toggle(
|
||||
}
|
||||
|
||||
async fn delete(
|
||||
pool: web::Data<PgPool>,
|
||||
pool: web::Data<SqlitePool>,
|
||||
params: web::Path<UpdateParams>,
|
||||
session: Session,
|
||||
) -> Result<HttpResponse, Error> {
|
||||
|
@ -1,19 +1,19 @@
|
||||
use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
|
||||
|
||||
use crate::model::{NewTask, Task};
|
||||
|
||||
pub async fn init_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
|
||||
PgPoolOptions::new()
|
||||
.connect_timeout(std::time::Duration::from_secs(2))
|
||||
pub async fn init_pool(database_url: &str) -> Result<SqlitePool, sqlx::Error> {
|
||||
SqlitePoolOptions::new()
|
||||
.connect_timeout(std::time::Duration::from_secs(1))
|
||||
.connect(database_url)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_all_tasks(pool: &PgPool) -> Result<Vec<Task>, &'static str> {
|
||||
pub async fn get_all_tasks(pool: &SqlitePool) -> Result<Vec<Task>, &'static str> {
|
||||
Task::all(pool).await.map_err(|_| "Error retrieving tasks")
|
||||
}
|
||||
|
||||
pub async fn create_task(todo: String, pool: &PgPool) -> Result<(), &'static str> {
|
||||
pub async fn create_task(todo: String, pool: &SqlitePool) -> Result<(), &'static str> {
|
||||
let new_task = NewTask { description: todo };
|
||||
Task::insert(new_task, pool)
|
||||
.await
|
||||
@ -21,14 +21,14 @@ pub async fn create_task(todo: String, pool: &PgPool) -> Result<(), &'static str
|
||||
.map_err(|_| "Error inserting task")
|
||||
}
|
||||
|
||||
pub async fn toggle_task(id: i32, pool: &PgPool) -> Result<(), &'static str> {
|
||||
pub async fn toggle_task(id: i32, pool: &SqlitePool) -> Result<(), &'static str> {
|
||||
Task::toggle_with_id(id, pool)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|_| "Error toggling task completion")
|
||||
}
|
||||
|
||||
pub async fn delete_task(id: i32, pool: &PgPool) -> Result<(), &'static str> {
|
||||
pub async fn delete_task(id: i32, pool: &SqlitePool) -> Result<(), &'static str> {
|
||||
Task::delete_with_id(id, pool)
|
||||
.await
|
||||
.map(|_| ())
|
||||
|
@ -20,16 +20,14 @@ static SESSION_SIGNING_KEY: &[u8] = &[0; 32];
|
||||
#[actix_web::main]
|
||||
async fn main() -> io::Result<()> {
|
||||
dotenv().ok();
|
||||
|
||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||
|
||||
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||
println!("{}", database_url);
|
||||
let pool = db::init_pool(&database_url)
|
||||
.await
|
||||
.expect("Failed to create pool");
|
||||
|
||||
log::info!("starting HTTP serer at http://localhost:8088");
|
||||
log::info!("starting HTTP serer at http://localhost:8080");
|
||||
|
||||
HttpServer::new(move || {
|
||||
log::debug!("Constructing the App");
|
||||
@ -59,7 +57,8 @@ async fn main() -> io::Result<()> {
|
||||
.service(web::resource("/todo/{id}").route(web::post().to(api::update)))
|
||||
.service(Files::new("/static", "./static/"))
|
||||
})
|
||||
.bind(("127.0.0.1", 8088))?
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.workers(2)
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
@ -1,19 +1,20 @@
|
||||
use sqlx::PgPool;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NewTask {
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct Task {
|
||||
pub id: i32,
|
||||
pub id: i64,
|
||||
pub description: String,
|
||||
pub completed: bool,
|
||||
}
|
||||
|
||||
impl Task {
|
||||
pub async fn all(connection: &PgPool) -> Result<Vec<Task>, sqlx::Error> {
|
||||
pub async fn all(connection: &SqlitePool) -> Result<Vec<Task>, sqlx::Error> {
|
||||
let tasks = sqlx::query_as!(
|
||||
Task,
|
||||
r#"
|
||||
@ -23,10 +24,14 @@ impl Task {
|
||||
)
|
||||
.fetch_all(connection)
|
||||
.await?;
|
||||
|
||||
Ok(tasks)
|
||||
}
|
||||
|
||||
pub async fn insert(todo: NewTask, connection: &PgPool) -> Result<(), sqlx::Error> {
|
||||
pub async fn insert(
|
||||
todo: NewTask,
|
||||
connection: &SqlitePool,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO tasks (description)
|
||||
@ -36,29 +41,31 @@ impl Task {
|
||||
)
|
||||
.execute(connection)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn toggle_with_id(
|
||||
id: i32,
|
||||
connection: &PgPool,
|
||||
connection: &SqlitePool,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query!(
|
||||
r#"
|
||||
UPDATE tasks
|
||||
SET completed = NOT completed
|
||||
WHERE id = $1
|
||||
"#,
|
||||
"#,
|
||||
id
|
||||
)
|
||||
.execute(connection)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn delete_with_id(
|
||||
id: i32,
|
||||
connection: &PgPool,
|
||||
connection: &SqlitePool,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query!(
|
||||
r#"
|
||||
@ -69,6 +76,7 @@ impl Task {
|
||||
)
|
||||
.execute(connection)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user