-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.rs
executable file
·140 lines (124 loc) · 4.26 KB
/
mod.rs
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
136
137
138
139
140
use std::ops::DerefMut;
use crate::db::Pool;
use async_graphql::*;
use serde::{Deserialize, Serialize};
use sqlx::{self, Row, postgres::PgRow};
use strum_macros::{Display, EnumString};
pub struct QueryRoot;
#[derive(
Clone, Copy, Debug, Deserialize, Display, Enum, Eq, EnumString, PartialEq, Serialize, sqlx::Type,
)]
#[sqlx(type_name = "chocolate_type")]
pub enum ChocolateType {
Bitter,
White,
Milk,
}
#[derive(SimpleObject, sqlx::FromRow)]
#[derive(Debug)]
struct Product {
id: i32,
name: String,
description: String,
price: i32,
chocolate_type: ChocolateType,
fillings: Vec<String>,
images: Vec<String>
}
#[Object]
impl QueryRoot {
async fn products(&self, ctx: &Context<'_>) -> FieldResult<Vec<Product>> {
let pool = ctx.data::<Pool>().unwrap();
let query_str = format!("select id, name, description, price, chocolate_type,
fillings, images from products order by id");
let result = sqlx::query(query_str.as_str())
.map(|row: PgRow| Product {
id: row.get("id"),
name: row.get("name"),
description: row.get("description"),
price: row.get("price"),
chocolate_type: row.get("chocolate_type"),
fillings: row.get("fillings"),
images: row.get("images"),
})
.fetch_all(pool.get().await.unwrap().deref_mut())
.await
.unwrap();
return Ok(result);
}
async fn product(&self, ctx: &Context<'_>, id: ID) -> FieldResult<Product> {
let pool = ctx.data::<Pool>().unwrap();
let query_str = format!("select id, name, description, price, chocolate_type,
fillings, images from products where id = {}", String::from(id));
let result = sqlx::query(query_str.as_str())
.map(|row: PgRow| Product {
id: row.get("id"),
name: row.get("name"),
description: row.get("description"),
price: row.get("price"),
chocolate_type: row.get("chocolate_type"),
fillings: row.get("fillings"),
images: row.get("images"),
})
.fetch_one(pool.get().await.unwrap().deref_mut())
.await
.unwrap();
return Ok(result);
}
}
pub struct MutationRoot;
#[Object]
impl MutationRoot {
async fn create_product(
&self,
ctx: &Context<'_>,
name: String,
description: String,
price: i32,
chocolate_type: ChocolateType,
fillings: Vec<String>,
images: Vec<String>,
) -> ID {
let pool = ctx.data::<Pool>().unwrap();
let query_str = format!("insert into products(name, description, price, chocolate_type, fillings, images)
values ('{}', '{}', {}, '{:?}', '{:?}', '{:?}') returning id", name, description, price, chocolate_type, fillings, images);
let query_str = query_str.replace("[", "{").replace("]", "}"); // handles arrays formatting
let result: Result<i32, sqlx::Error> = sqlx::query(query_str.as_str())
.map(|row: PgRow| row.get("id") )
.fetch_one(pool.get().await.unwrap().deref_mut())
.await;
let mut id: i32 = -1;
match result {
Ok(v) => {id = v; }
Err(e) => println!("Error creating new product: {}", e)
}
ID::from(id)
}
async fn update_product_price(
&self,
ctx: &Context<'_>,
id: ID,
new_price: i32,
) -> Result<bool> {
let pool = ctx.data::<Pool>().unwrap();
let query_str = format!("update products set price = {} where id = {}", new_price, String::from(id));
let result = sqlx::query(query_str.as_str())
.execute(pool.get().await.unwrap().deref_mut())
.await;
match result {
Ok(v) => { Ok(v.rows_affected() > 0) },
Err(e) => {println!("Error while updating: {}", e); Ok(false) }
}
}
async fn delete_product(&self, ctx: &Context<'_>, id: ID) -> Result<bool> {
let pool = ctx.data::<Pool>().unwrap();
let query_str = format!("delete from products where id = {}", String::from(id));
let result = sqlx::query(query_str.as_str())
.execute(pool.get().await.unwrap().deref_mut())
.await;
match result {
Ok(v) => { Ok(v.rows_affected() > 0) },
Err(e) => {println!("Error while deleting: {}", e); Ok(false) }
}
}
}