1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::convert::Infallible;
use warp::http::StatusCode;
use log::*;

use crate::db::{self, DbConn};
use crate::models::{ListOptions, Todo};

pub async fn list_todos(
    opts: ListOptions, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    // just return a json array of todos, applying the limit and offset 
    let todos: Vec<Todo> = db::get_all_todos(opts, db_conn).await;
    Ok( warp::reply::json(&todos))
}

pub async fn create_todo(
    todo: Todo, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    debug!("add_todo: {:?}", todo);
    let row_count = db::add_todo(&todo, db_conn).await;
    if row_count == 1 {
        debug!("{:?} todo added successfully", row_count);
        Ok(StatusCode::CREATED)
    } else {
        error!("error occurred in handlers::add_todo(..)");
        Ok(StatusCode::BAD_REQUEST)
    }
}

pub async fn update_todo(
    id: u32,
    mut todo: Todo,
    db_conn: DbConn,
) -> Result<impl warp::Reply, Infallible> {
    debug!("update todo: id = {}, todo = {:?}", id, todo);
    todo.id = id;
    match db::update_todo(&todo, db_conn).await {
        1 => Ok(StatusCode::OK),  // row count returned as 1
        _ => Ok(StatusCode::NOT_FOUND),
    }
}

pub async fn delete_todo(
    id: u32, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    debug!("delete todo: id = {}", id);
    match db::delete_todo(id, db_conn).await {
        1 => Ok(StatusCode::NO_CONTENT),  // row count returned as 1
        _ => Ok(StatusCode::NOT_FOUND),
    }
}

pub async fn get_todo(
    id: u32, 
    db_conn: DbConn
) -> Result<impl warp::Reply, Infallible> {
    // just return a json of todo for the given id 
    let todo: Todo = db::get_todo(id, db_conn).await;
    Ok( warp::reply::json(&todo))
}