File size: 3,464 Bytes
fde7cfe
 
 
 
 
 
 
 
 
7fd582a
 
fde7cfe
7fd582a
 
 
fde7cfe
 
7fd582a
 
 
 
fde7cfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use actix_web::{
    App, HttpResponse, HttpServer, Responder, delete, get, post, put,
    web::{self, Data, Json},
};
use serde::{Deserialize, Serialize};
use sqlx::{PgPool, prelude::FromRow};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    println!("START APP");

    dotenvy::dotenv().ok();

    println!("LOAD ENV");

    let pool = db().await;

    println!("DATABASE CONNECTED");

    println!("START SERVER");

    HttpServer::new(move || {
        App::new()
            .app_data(Data::new(pool.clone()))
            .service(todo_list)
            .service(add_todo)
            .service(get_single_todo)
            .service(delete_todo)
            .service(update_todo)
    })
    .bind(("0.0.0.0", 7860))?
    .run()
    .await
}

#[get("/todo_list")]
async fn todo_list(pool: web::Data<PgPool>) -> impl Responder {
    let todos: Vec<TodoSql> = sqlx::query_as("Select * FROM todos")
        .persistent(false)
        .fetch_all(pool.get_ref())
        .await
        .unwrap();

    let todos_json = serde_json::to_string_pretty(&todos).unwrap();

    HttpResponse::Ok().body(todos_json)
}

#[post("/add_todo")]
async fn add_todo(pool: web::Data<PgPool>, todo_req: Json<TodoReq>) -> impl Responder {
    sqlx::query("INSERT INTO todos (content) VALUES ($1)")
        .persistent(false)
        .bind(&todo_req.content)
        .execute(pool.get_ref())
        .await
        .unwrap();

    HttpResponse::Ok().body("Add new Todo")
}

#[get("/todo/{id}")]
async fn get_single_todo(pool: web::Data<PgPool>, path: web::Path<i32>) -> impl Responder {
    let id = path.into_inner();

    let rows: Vec<TodoSql> = sqlx::query_as("SELECT * FROM todos WHERE id = $1")
        .persistent(false)
        .bind(&id)
        .fetch_all(pool.get_ref())
        .await
        .unwrap();

    if rows.len() == 0 {
        let msg = format!("NO todo : id : {} found!", id);
        HttpResponse::NotFound().body(msg)
    } else {
        let todo_json = serde_json::to_string_pretty(&rows[0]).unwrap();
        HttpResponse::Ok().body(todo_json)
    }
}

#[delete("/delete/{id}")]
async fn delete_todo(pool: web::Data<PgPool>, path: web::Path<i32>) -> impl Responder {
    let id = path.into_inner();

    match sqlx::query("DELETE FROM todos WHERE id = $1")
        .persistent(false)
        .bind(&id)
        .execute(pool.get_ref())
        .await
    {
        Ok(_) => HttpResponse::Ok().body("Remove Todo!"),
        Err(err) => HttpResponse::InternalServerError().body(format!("Database Error: {}", err)),
    }
}

#[put("/update/{id}")]
async fn update_todo(
    pool: web::Data<PgPool>,
    path: web::Path<i32>,
    todo_req: Json<TodoReq>,
) -> impl Responder {
    let id = path.into_inner();

    match sqlx::query("UPDATE todos SET content = $1 WHERE id = $2")
        .persistent(false)
        .bind(&todo_req.content)
        .bind(&id)
        .execute(pool.get_ref())
        .await
    {
        Ok(_) => HttpResponse::Ok().body("Update Todo!"),
        Err(err) => HttpResponse::InternalServerError().body(format!("Database Error: {}", err)),
    }
}

async fn db() -> PgPool {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL not found");
    let pool = sqlx::postgres::PgPool::connect(&database_url)
        .await
        .unwrap();

    pool
}

#[derive(FromRow, Serialize)]
struct TodoSql {
    id: i32,
    content: String,
}

#[derive(Deserialize)]
struct TodoReq {
    content: String,
}