1
0
mirror of https://github.com/actix/examples synced 2025-01-23 06:14:35 +01:00

37 lines
1.1 KiB
Rust
Raw Normal View History

2022-02-06 07:55:51 +00:00
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
2018-08-27 10:56:26 +01:00
2019-03-10 18:23:44 -07:00
use crate::model::{NewTask, Task};
2018-08-27 10:56:26 +01:00
2022-02-06 07:55:51 +00:00
pub async fn init_pool(database_url: &str) -> Result<SqlitePool, sqlx::Error> {
SqlitePoolOptions::new()
2022-07-09 23:39:21 +01:00
.acquire_timeout(std::time::Duration::from_secs(1))
2022-02-05 17:34:43 +00:00
.connect(database_url)
.await
2018-08-27 10:56:26 +01:00
}
2022-02-06 07:55:51 +00:00
pub async fn get_all_tasks(pool: &SqlitePool) -> Result<Vec<Task>, &'static str> {
2022-02-05 17:34:43 +00:00
Task::all(pool).await.map_err(|_| "Error retrieving tasks")
2018-08-27 10:56:26 +01:00
}
2022-02-06 07:55:51 +00:00
pub async fn create_task(todo: String, pool: &SqlitePool) -> Result<(), &'static str> {
2019-03-10 18:23:44 -07:00
let new_task = NewTask { description: todo };
2022-02-05 17:34:43 +00:00
Task::insert(new_task, pool)
.await
2019-03-10 18:23:44 -07:00
.map(|_| ())
.map_err(|_| "Error inserting task")
2018-08-27 10:56:26 +01:00
}
2022-02-06 07:55:51 +00:00
pub async fn toggle_task(id: i32, pool: &SqlitePool) -> Result<(), &'static str> {
2022-02-05 17:34:43 +00:00
Task::toggle_with_id(id, pool)
.await
2019-03-10 18:23:44 -07:00
.map(|_| ())
.map_err(|_| "Error toggling task completion")
2018-08-27 10:56:26 +01:00
}
2022-02-06 07:55:51 +00:00
pub async fn delete_task(id: i32, pool: &SqlitePool) -> Result<(), &'static str> {
2022-02-05 17:34:43 +00:00
Task::delete_with_id(id, pool)
.await
2019-03-10 18:23:44 -07:00
.map(|_| ())
.map_err(|_| "Error deleting task")
2018-08-27 10:56:26 +01:00
}