amy-invitation commited on
Commit
fde7cfe
·
1 Parent(s): 3f218dc
Files changed (1) hide show
  1. src/main.rs +125 -0
src/main.rs ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use actix_web::{
2
+ App, HttpResponse, HttpServer, Responder, delete, get, post, put,
3
+ web::{self, Data, Json},
4
+ };
5
+ use serde::{Deserialize, Serialize};
6
+ use sqlx::{PgPool, prelude::FromRow};
7
+
8
+ #[actix_web::main]
9
+ async fn main() -> std::io::Result<()> {
10
+ dotenvy::dotenv().ok();
11
+ let pool = db().await;
12
+
13
+ HttpServer::new(move || {
14
+ App::new()
15
+ .app_data(Data::new(pool.clone()))
16
+ .service(todo_list)
17
+ .service(add_todo)
18
+ .service(get_single_todo)
19
+ .service(delete_todo)
20
+ .service(update_todo)
21
+ })
22
+ .bind(("0.0.0.0", 7860))?
23
+ .run()
24
+ .await
25
+ }
26
+
27
+ #[get("/todo_list")]
28
+ async fn todo_list(pool: web::Data<PgPool>) -> impl Responder {
29
+ let todos: Vec<TodoSql> = sqlx::query_as("Select * FROM todos")
30
+ .persistent(false)
31
+ .fetch_all(pool.get_ref())
32
+ .await
33
+ .unwrap();
34
+
35
+ let todos_json = serde_json::to_string_pretty(&todos).unwrap();
36
+
37
+ HttpResponse::Ok().body(todos_json)
38
+ }
39
+
40
+ #[post("/add_todo")]
41
+ async fn add_todo(pool: web::Data<PgPool>, todo_req: Json<TodoReq>) -> impl Responder {
42
+ sqlx::query("INSERT INTO todos (content) VALUES ($1)")
43
+ .persistent(false)
44
+ .bind(&todo_req.content)
45
+ .execute(pool.get_ref())
46
+ .await
47
+ .unwrap();
48
+
49
+ HttpResponse::Ok().body("Add new Todo")
50
+ }
51
+
52
+ #[get("/todo/{id}")]
53
+ async fn get_single_todo(pool: web::Data<PgPool>, path: web::Path<i32>) -> impl Responder {
54
+ let id = path.into_inner();
55
+
56
+ let rows: Vec<TodoSql> = sqlx::query_as("SELECT * FROM todos WHERE id = $1")
57
+ .persistent(false)
58
+ .bind(&id)
59
+ .fetch_all(pool.get_ref())
60
+ .await
61
+ .unwrap();
62
+
63
+ if rows.len() == 0 {
64
+ let msg = format!("NO todo : id : {} found!", id);
65
+ HttpResponse::NotFound().body(msg)
66
+ } else {
67
+ let todo_json = serde_json::to_string_pretty(&rows[0]).unwrap();
68
+ HttpResponse::Ok().body(todo_json)
69
+ }
70
+ }
71
+
72
+ #[delete("/delete/{id}")]
73
+ async fn delete_todo(pool: web::Data<PgPool>, path: web::Path<i32>) -> impl Responder {
74
+ let id = path.into_inner();
75
+
76
+ match sqlx::query("DELETE FROM todos WHERE id = $1")
77
+ .persistent(false)
78
+ .bind(&id)
79
+ .execute(pool.get_ref())
80
+ .await
81
+ {
82
+ Ok(_) => HttpResponse::Ok().body("Remove Todo!"),
83
+ Err(err) => HttpResponse::InternalServerError().body(format!("Database Error: {}", err)),
84
+ }
85
+ }
86
+
87
+ #[put("/update/{id}")]
88
+ async fn update_todo(
89
+ pool: web::Data<PgPool>,
90
+ path: web::Path<i32>,
91
+ todo_req: Json<TodoReq>,
92
+ ) -> impl Responder {
93
+ let id = path.into_inner();
94
+
95
+ match sqlx::query("UPDATE todos SET content = $1 WHERE id = $2")
96
+ .persistent(false)
97
+ .bind(&todo_req.content)
98
+ .bind(&id)
99
+ .execute(pool.get_ref())
100
+ .await
101
+ {
102
+ Ok(_) => HttpResponse::Ok().body("Update Todo!"),
103
+ Err(err) => HttpResponse::InternalServerError().body(format!("Database Error: {}", err)),
104
+ }
105
+ }
106
+
107
+ async fn db() -> PgPool {
108
+ let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL not found");
109
+ let pool = sqlx::postgres::PgPool::connect(&database_url)
110
+ .await
111
+ .unwrap();
112
+
113
+ pool
114
+ }
115
+
116
+ #[derive(FromRow, Serialize)]
117
+ struct TodoSql {
118
+ id: i32,
119
+ content: String,
120
+ }
121
+
122
+ #[derive(Deserialize)]
123
+ struct TodoReq {
124
+ content: String,
125
+ }