Skip to content

Use json! macro to simplify JSON serialization code #3889

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Sep 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
da37e26
errors::json: Use `json!` macro to simplify JSON serialization code
Turbo87 Sep 3, 2021
f285b17
controllers::helpers: Use `json!` macro to simplify JSON serializatio…
Turbo87 Sep 3, 2021
7c843f2
controllers::krate::downloads: Use `json!` macro to simplify JSON ser…
Turbo87 Sep 3, 2021
263c2d1
controllers::krate::follow: Use `json!` macro to simplify JSON serial…
Turbo87 Sep 3, 2021
e36d08e
controllers::krate::metadata: Use `json!` macro to simplify JSON seri…
Turbo87 Sep 3, 2021
f2b7e53
controllers::krate::owners: Use `json!` macro to simplify JSON serial…
Turbo87 Sep 3, 2021
0424d29
controllers::krate::search: Use `json!` macro to simplify JSON serial…
Turbo87 Sep 3, 2021
103f23c
controllers::user::me: Use `json!` macro to simplify JSON serializati…
Turbo87 Sep 3, 2021
611c5db
controllers::user::other: Use `json!` macro to simplify JSON serializ…
Turbo87 Sep 3, 2021
6438e7b
controllers::user::session: Use `json!` macro to simplify JSON serial…
Turbo87 Sep 3, 2021
37f111a
controllers::version::deprecated: Use `json!` macro to simplify JSON …
Turbo87 Sep 3, 2021
9fd5d56
controllers::version::downloads: Use `json!` macro to simplify JSON s…
Turbo87 Sep 3, 2021
c39e7d6
controllers::version::metadata: Use `json!` macro to simplify JSON se…
Turbo87 Sep 3, 2021
39283e6
controllers::category: Use `json!` macro to simplify JSON serializati…
Turbo87 Sep 3, 2021
43784d6
controllers::crate_owner_invitation: Use `json!` macro to simplify JS…
Turbo87 Sep 3, 2021
99e7ad8
controllers::keyword: Use `json!` macro to simplify JSON serializatio…
Turbo87 Sep 3, 2021
8726c20
controllers::site_metadata: Use `json!` macro to simplify JSON serial…
Turbo87 Sep 3, 2021
d450176
controllers::team: Use `json!` macro to simplify JSON serialization code
Turbo87 Sep 3, 2021
2c2536a
controllers::token: Use `json!` macro to simplify JSON serialization …
Turbo87 Sep 3, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 11 additions & 30 deletions src/controllers/category.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,18 @@ pub fn index(req: &mut dyn RequestExt) -> EndpointResult {
let conn = req.db_read_only()?;
let categories =
Category::toplevel(&conn, sort, i64::from(options.per_page), i64::from(offset))?;
let categories = categories.into_iter().map(Category::into).collect();
let categories = categories
.into_iter()
.map(Category::into)
.collect::<Vec<EncodableCategory>>();

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

#[derive(Serialize)]
struct R {
categories: Vec<EncodableCategory>,
meta: Meta,
}
#[derive(Serialize)]
struct Meta {
total: i64,
}

Ok(req.json(&R {
categories,
meta: Meta { total },
}))
Ok(req.json(&json!({
"categories": categories,
"meta": { "total": total },
})))
}

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

#[derive(Serialize)]
struct R {
category: EncodableCategoryWithSubcategories,
}
Ok(req.json(&R {
category: cat_with_subcats,
}))
Ok(req.json(&json!({ "category": cat_with_subcats })))
}

/// Handles the `GET /category_slugs` route.
pub fn slugs(req: &mut dyn RequestExt) -> EndpointResult {
let conn = req.db_read_only()?;
let slugs = categories::table
let slugs: Vec<Slug> = categories::table
.select((categories::slug, categories::slug, categories::description))
.order(categories::slug)
.load(&*conn)?;
Expand All @@ -91,11 +78,5 @@ pub fn slugs(req: &mut dyn RequestExt) -> EndpointResult {
description: String,
}

#[derive(Serialize)]
struct R {
category_slugs: Vec<Slug>,
}
Ok(req.json(&R {
category_slugs: slugs,
}))
Ok(req.json(&json!({ "category_slugs": slugs })))
}
35 changes: 10 additions & 25 deletions src/controllers/crate_owner_invitation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,10 @@ pub fn list(req: &mut dyn RequestExt) -> EndpointResult {
})
.collect::<AppResult<Vec<EncodableCrateOwnerInvitationV1>>>()?;

#[derive(Serialize)]
struct R {
crate_owner_invitations: Vec<EncodableCrateOwnerInvitationV1>,
users: Vec<EncodablePublicUser>,
}
Ok(req.json(&R {
crate_owner_invitations,
users,
}))
Ok(req.json(&json!({
"crate_owner_invitations": crate_owner_invitations,
"users": users,
})))
}

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

#[derive(Serialize)]
struct R {
crate_owner_invitation: InvitationResponse,
}
Ok(req.json(&R {
crate_owner_invitation: crate_invite,
}))
Ok(req.json(&json!({ "crate_owner_invitation": crate_invite })))
}

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

#[derive(Serialize)]
struct R {
crate_owner_invitation: InvitationResponse,
}
Ok(req.json(&R {
crate_owner_invitation: InvitationResponse {
crate_id,
accepted: true,
Ok(req.json(&json!({
"crate_owner_invitation": {
"crate_id": crate_id,
"accepted": true,
},
}))
})))
}
8 changes: 2 additions & 6 deletions src/controllers/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ pub(crate) mod pagination;
pub(crate) use self::pagination::Paginate;

pub fn ok_true() -> EndpointResult {
#[derive(Serialize)]
struct R {
ok: bool,
}

Ok(json_response(&R { ok: true }))
let json = json!({ "ok": true });
Ok(json_response(&json))
}
31 changes: 10 additions & 21 deletions src/controllers/keyword.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,15 @@ pub fn index(req: &mut dyn RequestExt) -> EndpointResult {
let conn = req.db_read_only()?;
let data: Paginated<Keyword> = query.load(&*conn)?;
let total = data.total();
let kws = data.into_iter().map(Keyword::into).collect::<Vec<_>>();

#[derive(Serialize)]
struct R {
keywords: Vec<EncodableKeyword>,
meta: Meta,
}
#[derive(Serialize)]
struct Meta {
total: Option<i64>,
}

Ok(req.json(&R {
keywords: kws,
meta: Meta { total: Some(total) },
}))
let kws = data
.into_iter()
.map(Keyword::into)
.collect::<Vec<EncodableKeyword>>();

Ok(req.json(&json!({
"keywords": kws,
"meta": { "total": total },
})))
}

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

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

#[derive(Serialize)]
struct R {
keyword: EncodableKeyword,
}
Ok(req.json(&R { keyword: kw.into() }))
Ok(req.json(&json!({ "keyword": EncodableKeyword::from(kw) })))
}
25 changes: 8 additions & 17 deletions src/controllers/krate/downloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub fn downloads(req: &mut dyn RequestExt) -> EndpointResult {
.load(&*conn)?
.into_iter()
.map(VersionDownload::into)
.collect::<Vec<_>>();
.collect::<Vec<EncodableVersionDownload>>();

let sum_downloads = sql::<BigInt>("SUM(version_downloads.downloads)");
let extra: Vec<ExtraDownload> = VersionDownload::belonging_to(rest)
Expand All @@ -50,20 +50,11 @@ pub fn downloads(req: &mut dyn RequestExt) -> EndpointResult {
date: String,
downloads: i64,
}
#[derive(Serialize)]
struct R {
version_downloads: Vec<EncodableVersionDownload>,
meta: Meta,
}
#[derive(Serialize)]
struct Meta {
extra_downloads: Vec<ExtraDownload>,
}
let meta = Meta {
extra_downloads: extra,
};
Ok(req.json(&R {
version_downloads: downloads,
meta,
}))

Ok(req.json(&json!({
"version_downloads": downloads,
"meta": {
"extra_downloads": extra,
},
})))
}
9 changes: 3 additions & 6 deletions src/controllers/krate/follow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,8 @@ pub fn following(req: &mut dyn RequestExt) -> EndpointResult {
let user_id = req.authenticate()?.forbid_api_token_auth()?.user_id();
let conn = req.db_read_only()?;
let follow = follow_target(req, &conn, user_id)?;
let following = diesel::select(exists(follows::table.find(follow.id()))).get_result(&*conn)?;
let following =
diesel::select(exists(follows::table.find(follow.id()))).get_result::<bool>(&*conn)?;

#[derive(Serialize)]
struct R {
following: bool,
}
Ok(req.json(&R { following }))
Ok(req.json(&json!({ "following": following })))
}
99 changes: 31 additions & 68 deletions src/controllers/krate/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ pub fn summary(req: &mut dyn RequestExt) -> EndpointResult {
use crate::schema::crates::dsl::*;

let conn = req.db_read_only()?;
let num_crates = crates.count().get_result(&*conn)?;
let num_downloads = metadata::table
let num_crates: i64 = crates.count().get_result(&*conn)?;
let num_downloads: i64 = metadata::table
.select(metadata::total_downloads)
.get_result(&*conn)?;

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

let popular_categories = Category::toplevel(&conn, "crates", 10, 0)?
.into_iter()
.map(Category::into)
.collect();

#[derive(Serialize)]
struct R {
num_downloads: i64,
num_crates: i64,
new_crates: Vec<EncodableCrate>,
most_downloaded: Vec<EncodableCrate>,
most_recently_downloaded: Vec<EncodableCrate>,
just_updated: Vec<EncodableCrate>,
popular_keywords: Vec<EncodableKeyword>,
popular_categories: Vec<EncodableCategory>,
}
Ok(req.json(&R {
num_downloads,
num_crates,
new_crates: encode_crates(new_crates)?,
most_downloaded: encode_crates(most_downloaded)?,
most_recently_downloaded: encode_crates(most_recently_downloaded)?,
just_updated: encode_crates(just_updated)?,
popular_keywords,
popular_categories,
}))
.collect::<Vec<EncodableCategory>>();

Ok(req.json(&json!({
"num_downloads": num_downloads,
"num_crates": num_crates,
"new_crates": encode_crates(new_crates)?,
"most_downloaded": encode_crates(most_downloaded)?,
"most_recently_downloaded": encode_crates(most_recently_downloaded)?,
"just_updated": encode_crates(just_updated)?,
"popular_keywords": popular_keywords,
"popular_categories": popular_categories,
})))
}

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

#[derive(Serialize)]
struct R {
#[serde(rename = "crate")]
krate: EncodableCrate,
versions: Vec<EncodableVersion>,
keywords: Vec<EncodableKeyword>,
categories: Vec<EncodableCategory>,
}
Ok(req.json(&R {
krate: EncodableCrate::from(
Ok(req.json(&json!({
"crate": EncodableCrate::from(
krate.clone(),
&top_versions,
Some(ids),
Expand All @@ -186,13 +167,13 @@ pub fn show(req: &mut dyn RequestExt) -> EndpointResult {
false,
recent_downloads,
),
versions: versions_publishers_and_audit_actions
"versions": versions_publishers_and_audit_actions
.into_iter()
.map(|(v, pb, aas)| EncodableVersion::from(v, &krate.name, pb, aas))
.collect(),
keywords: kws.into_iter().map(Keyword::into).collect(),
categories: cats.into_iter().map(Category::into).collect(),
}))
.collect::<Vec<_>>(),
"keywords": kws.into_iter().map(Keyword::into).collect::<Vec<EncodableKeyword>>(),
"categories": cats.into_iter().map(Category::into).collect::<Vec<EncodableCategory>>(),
})))
}

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

if req.wants_json() {
#[derive(Serialize)]
struct R {
url: String,
}
Ok(req.json(&R { url: redirect_url }))
Ok(req.json(&json!({ "url": redirect_url })))
} else {
Ok(req.redirect(redirect_url))
}
Expand Down Expand Up @@ -242,13 +219,9 @@ pub fn versions(req: &mut dyn RequestExt) -> EndpointResult {
.into_iter()
.zip(VersionOwnerAction::for_versions(&conn, &versions)?.into_iter())
.map(|((v, pb), aas)| EncodableVersion::from(v, crate_name, pb, aas))
.collect();
.collect::<Vec<_>>();

#[derive(Serialize)]
struct R {
versions: Vec<EncodableVersion>,
}
Ok(req.json(&R { versions }))
Ok(req.json(&json!({ "versions": versions })))
}

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

#[derive(Serialize)]
struct R {
dependencies: Vec<EncodableDependency>,
versions: Vec<EncodableVersion>,
meta: Meta,
}
#[derive(Serialize)]
struct Meta {
total: i64,
}
Ok(req.json(&R {
dependencies: rev_deps,
versions,
meta: Meta { total },
}))
Ok(req.json(&json!({
"dependencies": rev_deps,
"versions": versions,
"meta": { "total": total },
})))
}
Loading