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

37 lines
1.1 KiB
Rust
Raw Normal View History

2022-02-05 17:34:43 +00:00
use sqlx::postgres::{PgPool, PgPoolOptions};
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-05 17:34:43 +00:00
pub async fn init_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
PgPoolOptions::new()
.connect_timeout(std::time::Duration::from_secs(2))
.connect(database_url)
.await
2018-08-27 10:56:26 +01:00
}
2022-02-05 17:34:43 +00:00
pub async fn get_all_tasks(pool: &PgPool) -> Result<Vec<Task>, &'static str> {
Task::all(pool).await.map_err(|_| "Error retrieving tasks")
2018-08-27 10:56:26 +01:00
}
2022-02-05 17:34:43 +00:00
pub async fn create_task(todo: String, pool: &PgPool) -> 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-05 17:34:43 +00:00
pub async fn toggle_task(id: i32, pool: &PgPool) -> Result<(), &'static str> {
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-05 17:34:43 +00:00
pub async fn delete_task(id: i32, pool: &PgPool) -> Result<(), &'static str> {
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
}