Skip to content

Commit

Permalink
Refactor: Change semantics and remove redundant function
Browse files Browse the repository at this point in the history
  • Loading branch information
aryansri-19 committed Jul 5, 2024
1 parent 184ea61 commit 814fb7d
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 68 deletions.
10 changes: 5 additions & 5 deletions src/bin/todo/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,25 @@ pub struct Args {}

pub async fn command(_args: &Args) {
let task = Task {
description: inquire::prompt_text("Description").expect("An error occurred!"),
description: inquire::prompt_text("Description:").expect("An error occurred!"),
difficulty: Select::new(
"Difficulty",
"Difficulty:",
vec![Difficulty::Low, Difficulty::Medium, Difficulty::High],
)
.prompt_skippable()
.expect("An error occurred!"),
priority: Select::new(
"Priority",
"Priority:",
vec![Priority::Low, Priority::Medium, Priority::High],
)
.prompt_skippable()
.expect("An error occurred!"),
deadline: DateSelect::new("Deadline")
deadline: DateSelect::new("Deadline:")
.with_min_date(Local::now().date_naive())
.with_week_start(Weekday::Mon)
.prompt_skippable()
.expect("An error occurred!"),
};

task.insert_todo().await.expect("Failed to insert task");
task.save_to_db().await.expect("Failed to insert task");
}
6 changes: 3 additions & 3 deletions src/bin/todo/delete.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use clap::Parser;
use inquire::Select;
use mindmap::db::get_all_tasks;
use mindmap::Task;

#[derive(Parser)]
pub struct Args {}

pub async fn command(_args: &Args) {
let tasks = get_all_tasks()
let tasks = Task::list_tasks(false)
.await
.expect("Internal Server Error. Try Again!");

Expand All @@ -22,5 +22,5 @@ pub async fn command(_args: &Args) {
.find(|task| task.description == *task_description)
.expect("Task not found!");

task.delete_task().await.expect("Failed to delete task");
task.delete_from_db().await.expect("Failed to delete task");
}
2 changes: 1 addition & 1 deletion src/bin/todo/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use mindmap::Task;
pub struct Args {}

pub async fn command(_args: &Args) {
let rows = Task::list_tasks()
let rows = Task::list_tasks(true)
.await
.expect("Failed to fetch all tasks.");

Expand Down
36 changes: 9 additions & 27 deletions src/bin/todo/update.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use chrono::{Local, Weekday};
use clap::Parser;
use mindmap::db::get_all_tasks;
use mindmap::{Difficulty, Priority, Task};
use mindmap::Task;
use mindmap::{Difficulty, Priority};

#[derive(Parser)]
pub struct Args {}

pub async fn command(_args: &Args) {
let tasks = get_all_tasks()
let tasks = Task::list_tasks(false)
.await
.expect("Internal Server Error. Try Again!");

Expand All @@ -16,51 +16,33 @@ pub async fn command(_args: &Args) {
return;
};

let task_choices: Vec<String> = tasks
.iter()
.map(|task| {
format!(
"\nDescription: {}\nDifficulty: {}\nPriority: {}\nDeadline: {}",
task.description,
task.difficulty
.as_ref()
.map_or("Not set".to_string(), |d| d.to_string()),
task.priority
.as_ref()
.map_or("Not set".to_string(), |p| p.to_string()),
task.deadline
.map_or("Not set".to_string(), |d| d.to_string())
)
})
.collect();

let task_description = inquire::Select::new("Select the task to update:", task_choices)
let old_task = inquire::Select::new("Select the task to update:", tasks)
.prompt()
.expect("An error occurred!");

let new_task = Task {
description: inquire::prompt_text("New Description").expect("An error occurred!"),
description: inquire::prompt_text("New Description:").expect("An error occurred!"),
difficulty: inquire::Select::new(
"New Difficulty",
"New Difficulty:",
vec![Difficulty::Low, Difficulty::Medium, Difficulty::High],
)
.prompt_skippable()
.expect("An error occurred!"),
priority: inquire::Select::new(
"New Priority",
"New Priority:",
vec![Priority::Low, Priority::Medium, Priority::High],
)
.prompt_skippable()
.expect("An error occurred!"),
deadline: inquire::DateSelect::new("New Deadline")
deadline: inquire::DateSelect::new("New Deadline:")
.with_min_date(Local::now().date_naive())
.with_week_start(Weekday::Mon)
.prompt_skippable()
.expect("An error occurred!"),
};

new_task
.update_task(task_description)
.update_task(old_task.description)
.await
.expect("Failed to update task");
}
26 changes: 0 additions & 26 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ use dotenv::dotenv;
use tokio::sync::OnceCell;
use tokio_postgres::{Client, Error, NoTls};

use crate::Task;

static CLIENT: OnceCell<Client> = OnceCell::const_new();

async fn init_client() -> Result<Client, Error> {
Expand All @@ -26,27 +24,3 @@ async fn init_client() -> Result<Client, Error> {
pub async fn get_client() -> Result<&'static Client, Error> {
CLIENT.get_or_try_init(init_client).await
}

pub async fn get_all_tasks() -> Result<Vec<Task>, Error> {
let client = get_client().await?;

let rows = client
.query(
"SELECT description, priority, difficulty, deadline FROM todo",
&[],
)
.await
.expect("Failed to fetch all tasks.");

let tasks: Vec<Task> = rows
.iter()
.map(|row| Task {
description: row.get(0),
priority: row.get(1),
difficulty: row.get(2),
deadline: row.get(3),
})
.collect();

Ok(tasks)
}
30 changes: 24 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,18 @@ pub struct Task {
pub deadline: Option<NaiveDate>,
}

impl fmt::Display for Task {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"\nTask: {}\nPriority: {:?}\nDifficulty: {:?}\nDeadline: {:?}\n",
self.description, self.priority, self.difficulty, self.deadline
)
}
}

impl Task {
pub async fn insert_todo(&self) -> Result<(), Box<dyn Error>> {
pub async fn save_to_db(&self) -> Result<(), Box<dyn Error>> {
let client = get_client().await?;

client
Expand All @@ -165,7 +175,7 @@ impl Task {
Ok(())
}

pub async fn delete_task(&self) -> Result<(), Box<dyn Error>> {
pub async fn delete_from_db(&self) -> Result<(), Box<dyn Error>> {
let client = get_client().await?;

client
Expand All @@ -181,17 +191,25 @@ impl Task {
Ok(())
}

pub async fn list_tasks() -> Result<Vec<Task>, Box<dyn Error>> {
pub async fn list_tasks(current: bool) -> Result<Vec<Task>, Box<dyn Error>> {
let client = get_client().await?;

let today = Local::now().date_naive();
let rows = client
.query(
let (query, params): (&str, &[&(dyn ToSql + Sync)]) = if current {
(
"SELECT description, priority, difficulty, deadline FROM todo WHERE deadline = $1::date",
&[&today],
)
} else {
(
"SELECT description, priority, difficulty, deadline FROM todo",
&[],
)
};
let rows = client
.query(query, params)
.await
.expect("Failed to fetch all tasks.");
.expect("Failed to fetch tasks.");

let tasks: Vec<Task> = rows
.iter()
Expand Down

0 comments on commit 814fb7d

Please sign in to comment.