Skip to content

Commit 785e6b1

Browse files
committed
Add rustfmt
1 parent 489e9e2 commit 785e6b1

35 files changed

+2494
-573
lines changed

Diff for: ch_02/Cargo.lock

+170-251
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: ch_07/rustfmt.toml

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
max_width = 75

Diff for: ch_07/src/main.rs

+17-6
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,26 @@
11
#![warn(clippy::all)]
22

3-
use warp::{http::Method, Filter};
43
use handle_errors::return_error;
54
use tracing_subscriber::fmt::format::FmtSpan;
5+
use warp::{http::Method, Filter};
66

77
mod routes;
8-
mod types;
98
mod store;
9+
mod types;
1010

1111
#[tokio::main]
1212
async fn main() {
13-
let log_filter = std::env::var("RUST_LOG").unwrap_or_else(|_| "handle_errors=warn,practical_rust_book=warn,warp=warn".to_owned());
13+
let log_filter = std::env::var("RUST_LOG").unwrap_or_else(|_| {
14+
"handle_errors=warn,practical_rust_book=warn,warp=warn".to_owned()
15+
});
1416

15-
let store = store::Store::new("postgres://localhost:5432/rustwebdev").await;
17+
let store =
18+
store::Store::new("postgres://localhost:5432/rustwebdev").await;
1619

17-
sqlx::migrate!().run(&store.clone().connection).await.expect("Cannot migrate DB");
20+
sqlx::migrate!()
21+
.run(&store.clone().connection)
22+
.await
23+
.expect("Cannot migrate DB");
1824

1925
let store_filter = warp::any().map(move || store.clone());
2026

@@ -29,7 +35,12 @@ async fn main() {
2935
let cors = warp::cors()
3036
.allow_any_origin()
3137
.allow_header("content-type")
32-
.allow_methods(&[Method::PUT, Method::DELETE, Method::GET, Method::POST]);
38+
.allow_methods(&[
39+
Method::PUT,
40+
Method::DELETE,
41+
Method::GET,
42+
Method::POST,
43+
]);
3344

3445
let get_questions = warp::get()
3546
.and(warp::path("questions"))

Diff for: ch_07/src/routes/answer.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ pub async fn add_answer(
88
new_answer: NewAnswer,
99
) -> Result<impl warp::Reply, warp::Rejection> {
1010
match store.add_answer(new_answer).await {
11-
Ok(_) => Ok(warp::reply::with_status("Answer added", StatusCode::OK)),
11+
Ok(_) => {
12+
Ok(warp::reply::with_status("Answer added", StatusCode::OK))
13+
}
1214
Err(e) => Err(warp::reject::custom(e)),
1315
}
1416
}

Diff for: ch_07/src/routes/question.rs

+14-7
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
use std::collections::HashMap;
22

3+
use tracing::{event, instrument, Level};
34
use warp::http::StatusCode;
4-
use tracing::{instrument, event, Level};
55

66
use crate::store::Store;
7-
use crate::types::pagination::{Pagination, extract_pagination};
8-
use crate::types::question::{Question, NewQuestion};
7+
use crate::types::pagination::{extract_pagination, Pagination};
8+
use crate::types::question::{NewQuestion, Question};
99

1010
#[instrument]
1111
pub async fn get_questions(
@@ -20,7 +20,10 @@ pub async fn get_questions(
2020
pagination = extract_pagination(params)?;
2121
}
2222

23-
match store.get_questions(pagination.limit, pagination.offset).await {
23+
match store
24+
.get_questions(pagination.limit, pagination.offset)
25+
.await
26+
{
2427
Ok(res) => Ok(warp::reply::json(&res)),
2528
Err(e) => Err(warp::reject::custom(e)),
2629
}
@@ -37,13 +40,15 @@ pub async fn update_question(
3740
}
3841
}
3942

40-
4143
pub async fn delete_question(
4244
id: i32,
4345
store: Store,
4446
) -> Result<impl warp::Reply, warp::Rejection> {
4547
match store.delete_question(id).await {
46-
Ok(_) => Ok(warp::reply::with_status(format!("Question {} deleted", id), StatusCode::OK)),
48+
Ok(_) => Ok(warp::reply::with_status(
49+
format!("Question {} deleted", id),
50+
StatusCode::OK,
51+
)),
4752
Err(e) => Err(warp::reject::custom(e)),
4853
}
4954
}
@@ -53,7 +58,9 @@ pub async fn add_question(
5358
new_question: NewQuestion,
5459
) -> Result<impl warp::Reply, warp::Rejection> {
5560
match store.add_question(new_question).await {
56-
Ok(_) => Ok(warp::reply::with_status("Question added", StatusCode::OK)),
61+
Ok(_) => {
62+
Ok(warp::reply::with_status("Question added", StatusCode::OK))
63+
}
5764
Err(e) => Err(warp::reject::custom(e)),
5865
}
5966
}

Diff for: ch_07/src/store.rs

+109-77
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
use sqlx::postgres::{PgPoolOptions, PgPool, PgRow};
1+
use sqlx::postgres::{PgPool, PgPoolOptions, PgRow};
22
use sqlx::Row;
33

44
use handle_errors::Error;
55

66
use crate::types::{
7-
answer::{Answer, NewAnswer, AnswerId},
8-
question::{Question, QuestionId, NewQuestion},
7+
answer::{Answer, AnswerId, NewAnswer},
8+
question::{NewQuestion, Question, QuestionId},
99
};
1010

1111
#[derive(Debug, Clone)]
@@ -16,111 +16,143 @@ pub struct Store {
1616
impl Store {
1717
pub async fn new(db_url: &str) -> Self {
1818
let db_pool = match PgPoolOptions::new()
19-
.max_connections(5)
20-
.connect(db_url).await {
19+
.max_connections(5)
20+
.connect(db_url)
21+
.await
22+
{
2123
Ok(pool) => pool,
2224
Err(e) => panic!("Couldn't establish DB connection: {}", e),
2325
};
24-
26+
2527
Store {
2628
connection: db_pool,
2729
}
2830
}
2931

30-
pub async fn get_questions(&self, limit: Option<u32>, offset: u32) -> Result<Vec<Question>, Error> {
32+
pub async fn get_questions(
33+
&self,
34+
limit: Option<u32>,
35+
offset: u32,
36+
) -> Result<Vec<Question>, Error> {
3137
match sqlx::query("SELECT * from questions LIMIT $1 OFFSET $2")
3238
.bind(limit)
3339
.bind(offset)
3440
.map(|row: PgRow| Question {
35-
id: QuestionId(row.get("id")),
41+
id: QuestionId(row.get("id")),
3642
title: row.get("title"),
37-
content: row.get("content"),
43+
content: row.get("content"),
3844
tags: row.get("tags"),
39-
})
45+
})
4046
.fetch_all(&self.connection)
41-
.await {
42-
Ok(questions) => Ok(questions),
43-
Err(e) => {
44-
tracing::event!(tracing::Level::ERROR, "{:?}", e);
45-
Err(Error::DatabaseQueryError)
46-
}
47+
.await
48+
{
49+
Ok(questions) => Ok(questions),
50+
Err(e) => {
51+
tracing::event!(tracing::Level::ERROR, "{:?}", e);
52+
Err(Error::DatabaseQueryError)
4753
}
54+
}
4855
}
4956

50-
pub async fn add_question(&self, new_question: NewQuestion) -> Result<Question, Error> {
51-
match sqlx::query("INSERT INTO questions (title, content, tags) VALUES ($1, $2, $3) RETURNING id, title, content, tags")
52-
.bind(new_question.title)
53-
.bind(new_question.content)
54-
.bind(new_question.tags)
55-
.map(|row: PgRow| Question {
56-
id: QuestionId(row.get("id")),
57-
title: row.get("title"),
58-
content: row.get("content"),
59-
tags: row.get("tags"),
60-
})
61-
.fetch_one(&self.connection)
62-
.await {
63-
Ok(question) => Ok(question),
64-
Err(e) => {
65-
tracing::event!(tracing::Level::ERROR, "{:?}", e);
66-
Err(Error::DatabaseQueryError)
67-
},
57+
pub async fn add_question(
58+
&self,
59+
new_question: NewQuestion,
60+
) -> Result<Question, Error> {
61+
match sqlx::query(
62+
"INSERT INTO questions (title, content, tags)
63+
VALUES ($1, $2, $3)
64+
RETURNING id, title, content, tags",
65+
)
66+
.bind(new_question.title)
67+
.bind(new_question.content)
68+
.bind(new_question.tags)
69+
.map(|row: PgRow| Question {
70+
id: QuestionId(row.get("id")),
71+
title: row.get("title"),
72+
content: row.get("content"),
73+
tags: row.get("tags"),
74+
})
75+
.fetch_one(&self.connection)
76+
.await
77+
{
78+
Ok(question) => Ok(question),
79+
Err(e) => {
80+
tracing::event!(tracing::Level::ERROR, "{:?}", e);
81+
Err(Error::DatabaseQueryError)
6882
}
83+
}
6984
}
7085

71-
pub async fn update_question(&self, question: Question, question_id: i32) -> Result<Question, Error> {
72-
match sqlx::query("UPDATE questions SET title = $1, content = $2, tags = $3
86+
pub async fn update_question(
87+
&self,
88+
question: Question,
89+
question_id: i32,
90+
) -> Result<Question, Error> {
91+
match sqlx::query(
92+
"UPDATE questions SET title = $1, content = $2, tags = $3
7393
WHERE id = $4
74-
RETURNING id, title, content, tags")
75-
.bind(question.title)
76-
.bind(question.content)
77-
.bind(question.tags)
78-
.bind(question_id)
79-
.map(|row: PgRow| Question {
80-
id: QuestionId(row.get("id")),
81-
title: row.get("title"),
82-
content: row.get("content"),
83-
tags: row.get("tags"),
84-
})
85-
.fetch_one(&self.connection)
86-
.await {
87-
Ok(question) => Ok(question),
88-
Err(e) => {
89-
tracing::event!(tracing::Level::ERROR, "{:?}", e);
90-
Err(Error::DatabaseQueryError)
91-
},
94+
RETURNING id, title, content, tags",
95+
)
96+
.bind(question.title)
97+
.bind(question.content)
98+
.bind(question.tags)
99+
.bind(question_id)
100+
.map(|row: PgRow| Question {
101+
id: QuestionId(row.get("id")),
102+
title: row.get("title"),
103+
content: row.get("content"),
104+
tags: row.get("tags"),
105+
})
106+
.fetch_one(&self.connection)
107+
.await
108+
{
109+
Ok(question) => Ok(question),
110+
Err(e) => {
111+
tracing::event!(tracing::Level::ERROR, "{:?}", e);
112+
Err(Error::DatabaseQueryError)
92113
}
114+
}
93115
}
94116

95-
pub async fn delete_question(&self, question_id: i32) -> Result<bool, Error> {
117+
pub async fn delete_question(
118+
&self,
119+
question_id: i32,
120+
) -> Result<bool, Error> {
96121
match sqlx::query("DELETE FROM questions WHERE id = $1")
97122
.bind(question_id)
98123
.execute(&self.connection)
99-
.await {
100-
Ok(_) => Ok(true),
101-
Err(e) => {
102-
tracing::event!(tracing::Level::ERROR, "{:?}", e);
103-
Err(Error::DatabaseQueryError)
104-
},
124+
.await
125+
{
126+
Ok(_) => Ok(true),
127+
Err(e) => {
128+
tracing::event!(tracing::Level::ERROR, "{:?}", e);
129+
Err(Error::DatabaseQueryError)
105130
}
131+
}
106132
}
107133

108-
pub async fn add_answer(&self, new_answer: NewAnswer) -> Result<Answer, Error> {
109-
match sqlx::query("INSERT INTO answers (content, question_id) VALUES ($1, $2)")
110-
.bind(new_answer.content)
111-
.bind(new_answer.question_id.0)
112-
.map(|row: PgRow| Answer {
113-
id: AnswerId(row.get("id")),
114-
content: row.get("content"),
115-
question_id: QuestionId(row.get("question_id")),
116-
})
117-
.fetch_one(&self.connection)
118-
.await {
119-
Ok(answer) => Ok(answer),
120-
Err(e) => {
121-
tracing::event!(tracing::Level::ERROR, "{:?}", e);
122-
Err(Error::DatabaseQueryError)
123-
},
134+
pub async fn add_answer(
135+
&self,
136+
new_answer: NewAnswer,
137+
) -> Result<Answer, Error> {
138+
match sqlx::query(
139+
"INSERT INTO answers (content, question_id) VALUES ($1, $2)",
140+
)
141+
.bind(new_answer.content)
142+
.bind(new_answer.question_id.0)
143+
.map(|row: PgRow| Answer {
144+
id: AnswerId(row.get("id")),
145+
content: row.get("content"),
146+
question_id: QuestionId(row.get("question_id")),
147+
})
148+
.fetch_one(&self.connection)
149+
.await
150+
{
151+
Ok(answer) => Ok(answer),
152+
Err(e) => {
153+
tracing::event!(tracing::Level::ERROR, "{:?}", e);
154+
Err(Error::DatabaseQueryError)
124155
}
156+
}
125157
}
126158
}

Diff for: ch_07/src/types/answer.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@ pub struct AnswerId(pub i32);
1616
pub struct NewAnswer {
1717
pub content: String,
1818
pub question_id: QuestionId,
19-
}
19+
}

Diff for: ch_07/src/types/pagination.rs

+12-9
Original file line numberDiff line numberDiff line change
@@ -20,31 +20,34 @@ pub struct Pagination {
2020
/// # Example usage
2121
/// ```rust
2222
/// use std::collections::HashMap;
23-
///
23+
///
2424
/// let mut query = HashMap::new();
2525
/// query.insert("limit".to_string(), "1".to_string());
2626
/// query.insert("offset".to_string(), "10".to_string());
2727
/// let p = pagination::extract_pagination(query).unwrap();
2828
/// assert_eq!(p.limit, Some(1));
2929
/// assert_eq!(p.offset, 10);
3030
/// ```
31-
pub fn extract_pagination(params: HashMap<String, String>) -> Result<Pagination, Error> {
31+
pub fn extract_pagination(
32+
params: HashMap<String, String>,
33+
) -> Result<Pagination, Error> {
3234
// Could be improved in the future
33-
if params.contains_key("limit") && params.contains_key("offset") {
35+
if params.contains_key("limit") && params.contains_key("offset") {
3436
return Ok(Pagination {
3537
// Takes the "limit" parameter in the query and tries to convert it to a number
36-
limit: Some(params
37-
.get("limit")
38-
.unwrap()
39-
.parse::<u32>()
40-
.map_err(Error::ParseError)?),
38+
limit: Some(
39+
params
40+
.get("limit")
41+
.unwrap()
42+
.parse::<u32>()
43+
.map_err(Error::ParseError)?,
44+
),
4145
// Takes the "offset" parameter in the query and tries to convert it to a number
4246
offset: params
4347
.get("offset")
4448
.unwrap()
4549
.parse::<u32>()
4650
.map_err(Error::ParseError)?,
47-
4851
});
4952
}
5053

0 commit comments

Comments
 (0)