-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.rs
212 lines (175 loc) · 6.27 KB
/
models.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use actix_web::{
body::BoxBody, dev::Payload, web::JsonBody, FromRequest, HttpRequest, HttpResponse, Responder,
};
use futures::{future::LocalBoxFuture, FutureExt};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
use crate::errors::{AppError, TaskError};
const FIND_BY_PATTERN: &'static str = include_str!("./../queries/find_by_pattern.sql");
const FIND_ONGOING: &'static str = include_str!("./../queries/find_ongoing.sql");
const FIND_ALL: &'static str = include_str!("./../queries/find_all.sql");
const FIND_BY_ID: &'static str = include_str!("./../queries/find_by_id.sql");
const INSERT: &'static str = include_str!("./../queries/insert.sql");
const UPDATE: &'static str = include_str!("./../queries/update.sql");
const DELETE: &'static str = include_str!("./../queries/delete.sql");
const DONE: &'static str = include_str!("./../queries/done.sql");
const UNDO: &'static str = include_str!("./../queries/undo.sql");
#[derive(Clone, Debug, Serialize, Deserialize, FromRow)]
pub(crate) struct Task {
pub(crate) id: i64,
pub(crate) title: String,
pub(crate) details: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct InsertTask {
pub(crate) non_empty_title: String,
pub(crate) details: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct UpdateTask {
pub(crate) id: i64,
pub(crate) new_title: String,
pub(crate) details: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct QueryTask {
pub(crate) title: String,
pub(crate) details: String,
}
impl InsertTask {
pub(crate) async fn insert(self, db_pool: &SqlitePool) -> Result<Task, AppError> {
let mut connection = db_pool.acquire().await?;
let result = sqlx::query(INSERT)
.bind(&self.non_empty_title)
.bind(&self.details)
.execute(&mut connection)
.await?;
let task = Task {
id: result.last_insert_rowid(),
title: self.non_empty_title,
details: self.details,
};
Ok(task)
}
fn validate(self) -> Result<Self, TaskError> {
if self.non_empty_title.trim().is_empty() {
Err(TaskError::EmptyTitle)
} else {
Ok(self)
}
}
}
impl UpdateTask {
pub(crate) async fn update(self, db_pool: &SqlitePool) -> Result<u64, AppError> {
let mut connection = db_pool.acquire().await?;
let result = sqlx::query(UPDATE)
.bind(&self.new_title)
.bind(&self.details)
.bind(&self.id)
.execute(&mut connection)
.await?;
Ok(result.rows_affected())
}
fn validate(self) -> Result<Self, TaskError> {
if self.new_title.trim().is_empty() {
Err(TaskError::EmptyTitle)
} else {
Ok(self)
}
}
}
impl Task {
pub(crate) async fn delete(db_pool: &SqlitePool, task_id: i64) -> Result<u64, AppError> {
let mut connection = db_pool.acquire().await?;
let result = sqlx::query(DELETE)
.bind(task_id)
.execute(&mut connection)
.await?;
Ok(result.rows_affected())
}
pub(crate) async fn done(pool: &SqlitePool, task_id: i64) -> Result<u64, AppError> {
let mut connection = pool.acquire().await?;
let result = sqlx::query(DONE)
.bind(task_id)
.execute(&mut connection)
.await?;
Ok(result.rows_affected())
}
pub(crate) async fn undo(db_pool: &SqlitePool, task_id: i64) -> Result<u64, AppError> {
let mut connection = db_pool.acquire().await?;
let result = sqlx::query(UNDO)
.bind(task_id)
.execute(&mut connection)
.await?;
Ok(result.rows_affected())
}
pub(crate) async fn find_all(db_pool: &SqlitePool) -> Result<Vec<Self>, AppError> {
let result = sqlx::query_as(FIND_ALL).fetch_all(db_pool).await?;
Ok(result)
}
pub(crate) async fn find_ongoing(db_pool: &SqlitePool) -> Result<Vec<Self>, AppError> {
let result = sqlx::query_as(FIND_ONGOING).fetch_all(db_pool).await?;
Ok(result)
}
pub(crate) async fn find_by_pattern(
db_pool: &SqlitePool,
search_pattern: &str,
) -> Result<Vec<Self>, AppError> {
let result = sqlx::query_as(FIND_BY_PATTERN)
.bind(search_pattern)
.fetch_all(db_pool)
.await?;
Ok(result)
}
pub(crate) async fn find_by_id(
db_pool: &SqlitePool,
task_id: i64,
) -> Result<Option<Self>, AppError> {
let result = sqlx::query_as(FIND_BY_ID)
.bind(task_id)
.fetch_optional(db_pool)
.await?;
Ok(result)
}
}
impl Responder for Task {
type Body = BoxBody;
fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> {
let response = match serde_json::to_string(&self) {
Ok(body) => {
// Create response and set content type
HttpResponse::Ok()
.content_type("application/json")
.body(body)
}
Err(fail) => HttpResponse::from_error(AppError::from(fail)),
};
response
}
}
impl FromRequest for InsertTask {
type Error = AppError;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
JsonBody::new(req, payload, None, false)
.limit(4056)
.map(|res: Result<InsertTask, _>| match res {
Ok(insert_task) => insert_task.validate().map_err(|fail| AppError::from(fail)),
Err(fail) => Err(AppError::from(fail)),
})
.boxed_local()
}
}
impl FromRequest for UpdateTask {
type Error = AppError;
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
JsonBody::new(req, payload, None, false)
.limit(4056)
.map(|res: Result<UpdateTask, _>| match res {
Ok(update_task) => update_task.validate().map_err(|fail| AppError::from(fail)),
Err(fail) => Err(AppError::from(fail)),
})
.boxed_local()
}
}