Skip to content

Commit c00bc1c

Browse files
committed
Auto merge of #3889 - Turbo87:json-macro, r=hi-rustin
Use `json!` macro to simplify JSON serialization code see https://docs.serde.rs/serde_json/macro.json.html I guess `+132 βˆ’349` speaks for itself πŸ˜…
2 parents f8ab731 + 2c2536a commit c00bc1c

19 files changed

+132
-349
lines changed

β€Žsrc/controllers/category.rs

+11-30
Original file line numberDiff line numberDiff line change
@@ -18,25 +18,18 @@ pub fn index(req: &mut dyn RequestExt) -> EndpointResult {
1818
let conn = req.db_read_only()?;
1919
let categories =
2020
Category::toplevel(&conn, sort, i64::from(options.per_page), i64::from(offset))?;
21-
let categories = categories.into_iter().map(Category::into).collect();
21+
let categories = categories
22+
.into_iter()
23+
.map(Category::into)
24+
.collect::<Vec<EncodableCategory>>();
2225

2326
// Query for the total count of categories
2427
let total = Category::count_toplevel(&conn)?;
2528

26-
#[derive(Serialize)]
27-
struct R {
28-
categories: Vec<EncodableCategory>,
29-
meta: Meta,
30-
}
31-
#[derive(Serialize)]
32-
struct Meta {
33-
total: i64,
34-
}
35-
36-
Ok(req.json(&R {
37-
categories,
38-
meta: Meta { total },
39-
}))
29+
Ok(req.json(&json!({
30+
"categories": categories,
31+
"meta": { "total": total },
32+
})))
4033
}
4134

4235
/// Handles the `GET /categories/:category_id` route.
@@ -67,19 +60,13 @@ pub fn show(req: &mut dyn RequestExt) -> EndpointResult {
6760
parent_categories: parents,
6861
};
6962

70-
#[derive(Serialize)]
71-
struct R {
72-
category: EncodableCategoryWithSubcategories,
73-
}
74-
Ok(req.json(&R {
75-
category: cat_with_subcats,
76-
}))
63+
Ok(req.json(&json!({ "category": cat_with_subcats })))
7764
}
7865

7966
/// Handles the `GET /category_slugs` route.
8067
pub fn slugs(req: &mut dyn RequestExt) -> EndpointResult {
8168
let conn = req.db_read_only()?;
82-
let slugs = categories::table
69+
let slugs: Vec<Slug> = categories::table
8370
.select((categories::slug, categories::slug, categories::description))
8471
.order(categories::slug)
8572
.load(&*conn)?;
@@ -91,11 +78,5 @@ pub fn slugs(req: &mut dyn RequestExt) -> EndpointResult {
9178
description: String,
9279
}
9380

94-
#[derive(Serialize)]
95-
struct R {
96-
category_slugs: Vec<Slug>,
97-
}
98-
Ok(req.json(&R {
99-
category_slugs: slugs,
100-
}))
81+
Ok(req.json(&json!({ "category_slugs": slugs })))
10182
}

β€Žsrc/controllers/crate_owner_invitation.rs

+10-25
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,10 @@ pub fn list(req: &mut dyn RequestExt) -> EndpointResult {
4444
})
4545
.collect::<AppResult<Vec<EncodableCrateOwnerInvitationV1>>>()?;
4646

47-
#[derive(Serialize)]
48-
struct R {
49-
crate_owner_invitations: Vec<EncodableCrateOwnerInvitationV1>,
50-
users: Vec<EncodablePublicUser>,
51-
}
52-
Ok(req.json(&R {
53-
crate_owner_invitations,
54-
users,
55-
}))
47+
Ok(req.json(&json!({
48+
"crate_owner_invitations": crate_owner_invitations,
49+
"users": users,
50+
})))
5651
}
5752

5853
/// Handles the `GET /api/private/crate_owner_invitations` route.
@@ -271,13 +266,7 @@ pub fn handle_invite(req: &mut dyn RequestExt) -> EndpointResult {
271266
invitation.decline(conn)?;
272267
}
273268

274-
#[derive(Serialize)]
275-
struct R {
276-
crate_owner_invitation: InvitationResponse,
277-
}
278-
Ok(req.json(&R {
279-
crate_owner_invitation: crate_invite,
280-
}))
269+
Ok(req.json(&json!({ "crate_owner_invitation": crate_invite })))
281270
}
282271

283272
/// Handles the `PUT /api/v1/me/crate_owner_invitations/accept/:token` route.
@@ -290,14 +279,10 @@ pub fn handle_invite_with_token(req: &mut dyn RequestExt) -> EndpointResult {
290279
let crate_id = invitation.crate_id;
291280
invitation.accept(&conn, config)?;
292281

293-
#[derive(Serialize)]
294-
struct R {
295-
crate_owner_invitation: InvitationResponse,
296-
}
297-
Ok(req.json(&R {
298-
crate_owner_invitation: InvitationResponse {
299-
crate_id,
300-
accepted: true,
282+
Ok(req.json(&json!({
283+
"crate_owner_invitation": {
284+
"crate_id": crate_id,
285+
"accepted": true,
301286
},
302-
}))
287+
})))
303288
}

β€Žsrc/controllers/helpers.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,6 @@ pub(crate) mod pagination;
55
pub(crate) use self::pagination::Paginate;
66

77
pub fn ok_true() -> EndpointResult {
8-
#[derive(Serialize)]
9-
struct R {
10-
ok: bool,
11-
}
12-
13-
Ok(json_response(&R { ok: true }))
8+
let json = json!({ "ok": true });
9+
Ok(json_response(&json))
1410
}

β€Žsrc/controllers/keyword.rs

+10-21
Original file line numberDiff line numberDiff line change
@@ -24,22 +24,15 @@ pub fn index(req: &mut dyn RequestExt) -> EndpointResult {
2424
let conn = req.db_read_only()?;
2525
let data: Paginated<Keyword> = query.load(&*conn)?;
2626
let total = data.total();
27-
let kws = data.into_iter().map(Keyword::into).collect::<Vec<_>>();
28-
29-
#[derive(Serialize)]
30-
struct R {
31-
keywords: Vec<EncodableKeyword>,
32-
meta: Meta,
33-
}
34-
#[derive(Serialize)]
35-
struct Meta {
36-
total: Option<i64>,
37-
}
38-
39-
Ok(req.json(&R {
40-
keywords: kws,
41-
meta: Meta { total: Some(total) },
42-
}))
27+
let kws = data
28+
.into_iter()
29+
.map(Keyword::into)
30+
.collect::<Vec<EncodableKeyword>>();
31+
32+
Ok(req.json(&json!({
33+
"keywords": kws,
34+
"meta": { "total": total },
35+
})))
4336
}
4437

4538
/// Handles the `GET /keywords/:keyword_id` route.
@@ -49,9 +42,5 @@ pub fn show(req: &mut dyn RequestExt) -> EndpointResult {
4942

5043
let kw = Keyword::find_by_keyword(&conn, name)?;
5144

52-
#[derive(Serialize)]
53-
struct R {
54-
keyword: EncodableKeyword,
55-
}
56-
Ok(req.json(&R { keyword: kw.into() }))
45+
Ok(req.json(&json!({ "keyword": EncodableKeyword::from(kw) })))
5746
}

β€Žsrc/controllers/krate/downloads.rs

+8-17
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ pub fn downloads(req: &mut dyn RequestExt) -> EndpointResult {
3232
.load(&*conn)?
3333
.into_iter()
3434
.map(VersionDownload::into)
35-
.collect::<Vec<_>>();
35+
.collect::<Vec<EncodableVersionDownload>>();
3636

3737
let sum_downloads = sql::<BigInt>("SUM(version_downloads.downloads)");
3838
let extra: Vec<ExtraDownload> = VersionDownload::belonging_to(rest)
@@ -50,20 +50,11 @@ pub fn downloads(req: &mut dyn RequestExt) -> EndpointResult {
5050
date: String,
5151
downloads: i64,
5252
}
53-
#[derive(Serialize)]
54-
struct R {
55-
version_downloads: Vec<EncodableVersionDownload>,
56-
meta: Meta,
57-
}
58-
#[derive(Serialize)]
59-
struct Meta {
60-
extra_downloads: Vec<ExtraDownload>,
61-
}
62-
let meta = Meta {
63-
extra_downloads: extra,
64-
};
65-
Ok(req.json(&R {
66-
version_downloads: downloads,
67-
meta,
68-
}))
53+
54+
Ok(req.json(&json!({
55+
"version_downloads": downloads,
56+
"meta": {
57+
"extra_downloads": extra,
58+
},
59+
})))
6960
}

β€Žsrc/controllers/krate/follow.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,8 @@ pub fn following(req: &mut dyn RequestExt) -> EndpointResult {
4949
let user_id = req.authenticate()?.forbid_api_token_auth()?.user_id();
5050
let conn = req.db_read_only()?;
5151
let follow = follow_target(req, &conn, user_id)?;
52-
let following = diesel::select(exists(follows::table.find(follow.id()))).get_result(&*conn)?;
52+
let following =
53+
diesel::select(exists(follows::table.find(follow.id()))).get_result::<bool>(&*conn)?;
5354

54-
#[derive(Serialize)]
55-
struct R {
56-
following: bool,
57-
}
58-
Ok(req.json(&R { following }))
55+
Ok(req.json(&json!({ "following": following })))
5956
}

β€Žsrc/controllers/krate/metadata.rs

+31-68
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ pub fn summary(req: &mut dyn RequestExt) -> EndpointResult {
2525
use crate::schema::crates::dsl::*;
2626

2727
let conn = req.db_read_only()?;
28-
let num_crates = crates.count().get_result(&*conn)?;
29-
let num_downloads = metadata::table
28+
let num_crates: i64 = crates.count().get_result(&*conn)?;
29+
let num_downloads: i64 = metadata::table
3030
.select(metadata::total_downloads)
3131
.get_result(&*conn)?;
3232

@@ -89,34 +89,23 @@ pub fn summary(req: &mut dyn RequestExt) -> EndpointResult {
8989
.load(&*conn)?
9090
.into_iter()
9191
.map(Keyword::into)
92-
.collect();
92+
.collect::<Vec<EncodableKeyword>>();
9393

9494
let popular_categories = Category::toplevel(&conn, "crates", 10, 0)?
9595
.into_iter()
9696
.map(Category::into)
97-
.collect();
98-
99-
#[derive(Serialize)]
100-
struct R {
101-
num_downloads: i64,
102-
num_crates: i64,
103-
new_crates: Vec<EncodableCrate>,
104-
most_downloaded: Vec<EncodableCrate>,
105-
most_recently_downloaded: Vec<EncodableCrate>,
106-
just_updated: Vec<EncodableCrate>,
107-
popular_keywords: Vec<EncodableKeyword>,
108-
popular_categories: Vec<EncodableCategory>,
109-
}
110-
Ok(req.json(&R {
111-
num_downloads,
112-
num_crates,
113-
new_crates: encode_crates(new_crates)?,
114-
most_downloaded: encode_crates(most_downloaded)?,
115-
most_recently_downloaded: encode_crates(most_recently_downloaded)?,
116-
just_updated: encode_crates(just_updated)?,
117-
popular_keywords,
118-
popular_categories,
119-
}))
97+
.collect::<Vec<EncodableCategory>>();
98+
99+
Ok(req.json(&json!({
100+
"num_downloads": num_downloads,
101+
"num_crates": num_crates,
102+
"new_crates": encode_crates(new_crates)?,
103+
"most_downloaded": encode_crates(most_downloaded)?,
104+
"most_recently_downloaded": encode_crates(most_recently_downloaded)?,
105+
"just_updated": encode_crates(just_updated)?,
106+
"popular_keywords": popular_keywords,
107+
"popular_categories": popular_categories,
108+
})))
120109
}
121110

122111
/// Handles the `GET /crates/:crate_id` route.
@@ -167,16 +156,8 @@ pub fn show(req: &mut dyn RequestExt) -> EndpointResult {
167156
.load(&*conn)?;
168157
let top_versions = krate.top_versions(&conn)?;
169158

170-
#[derive(Serialize)]
171-
struct R {
172-
#[serde(rename = "crate")]
173-
krate: EncodableCrate,
174-
versions: Vec<EncodableVersion>,
175-
keywords: Vec<EncodableKeyword>,
176-
categories: Vec<EncodableCategory>,
177-
}
178-
Ok(req.json(&R {
179-
krate: EncodableCrate::from(
159+
Ok(req.json(&json!({
160+
"crate": EncodableCrate::from(
180161
krate.clone(),
181162
&top_versions,
182163
Some(ids),
@@ -186,13 +167,13 @@ pub fn show(req: &mut dyn RequestExt) -> EndpointResult {
186167
false,
187168
recent_downloads,
188169
),
189-
versions: versions_publishers_and_audit_actions
170+
"versions": versions_publishers_and_audit_actions
190171
.into_iter()
191172
.map(|(v, pb, aas)| EncodableVersion::from(v, &krate.name, pb, aas))
192-
.collect(),
193-
keywords: kws.into_iter().map(Keyword::into).collect(),
194-
categories: cats.into_iter().map(Category::into).collect(),
195-
}))
173+
.collect::<Vec<_>>(),
174+
"keywords": kws.into_iter().map(Keyword::into).collect::<Vec<EncodableKeyword>>(),
175+
"categories": cats.into_iter().map(Category::into).collect::<Vec<EncodableCategory>>(),
176+
})))
196177
}
197178

198179
/// Handles the `GET /crates/:crate_id/:version/readme` route.
@@ -207,11 +188,7 @@ pub fn readme(req: &mut dyn RequestExt) -> EndpointResult {
207188
.readme_location(crate_name, version);
208189

209190
if req.wants_json() {
210-
#[derive(Serialize)]
211-
struct R {
212-
url: String,
213-
}
214-
Ok(req.json(&R { url: redirect_url }))
191+
Ok(req.json(&json!({ "url": redirect_url })))
215192
} else {
216193
Ok(req.redirect(redirect_url))
217194
}
@@ -242,13 +219,9 @@ pub fn versions(req: &mut dyn RequestExt) -> EndpointResult {
242219
.into_iter()
243220
.zip(VersionOwnerAction::for_versions(&conn, &versions)?.into_iter())
244221
.map(|((v, pb), aas)| EncodableVersion::from(v, crate_name, pb, aas))
245-
.collect();
222+
.collect::<Vec<_>>();
246223

247-
#[derive(Serialize)]
248-
struct R {
249-
versions: Vec<EncodableVersion>,
250-
}
251-
Ok(req.json(&R { versions }))
224+
Ok(req.json(&json!({ "versions": versions })))
252225
}
253226

254227
/// Handles the `GET /crates/:crate_id/reverse_dependencies` route.
@@ -288,21 +261,11 @@ pub fn reverse_dependencies(req: &mut dyn RequestExt) -> EndpointResult {
288261
.map(|((version, krate_name, published_by), actions)| {
289262
EncodableVersion::from(version, &krate_name, published_by, actions)
290263
})
291-
.collect();
264+
.collect::<Vec<_>>();
292265

293-
#[derive(Serialize)]
294-
struct R {
295-
dependencies: Vec<EncodableDependency>,
296-
versions: Vec<EncodableVersion>,
297-
meta: Meta,
298-
}
299-
#[derive(Serialize)]
300-
struct Meta {
301-
total: i64,
302-
}
303-
Ok(req.json(&R {
304-
dependencies: rev_deps,
305-
versions,
306-
meta: Meta { total },
307-
}))
266+
Ok(req.json(&json!({
267+
"dependencies": rev_deps,
268+
"versions": versions,
269+
"meta": { "total": total },
270+
})))
308271
}

0 commit comments

Comments
Β (0)