Skip to content

Replace more encodable() methods with From implementations #3133

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 12 commits into from
Dec 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 2 additions & 4 deletions src/controllers/keyword.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub fn index(req: &mut dyn RequestExt) -> EndpointResult {
let conn = req.db_conn()?;
let data: Paginated<Keyword> = query.load(&*conn)?;
let total = data.total();
let kws = data.into_iter().map(Keyword::encodable).collect::<Vec<_>>();
let kws = data.into_iter().map(Keyword::into).collect::<Vec<_>>();

#[derive(Serialize)]
struct R {
Expand Down Expand Up @@ -52,7 +52,5 @@ pub fn show(req: &mut dyn RequestExt) -> EndpointResult {
struct R {
keyword: EncodableKeyword,
}
Ok(req.json(&R {
keyword: kw.encodable(),
}))
Ok(req.json(&R { keyword: kw.into() }))
}
2 changes: 1 addition & 1 deletion src/controllers/krate/downloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub fn downloads(req: &mut dyn RequestExt) -> EndpointResult {
.order(version_downloads::date.asc())
.load(&*conn)?
.into_iter()
.map(VersionDownload::encodable)
.map(VersionDownload::into)
.collect::<Vec<_>>();

let sum_downloads = sql::<BigInt>("SUM(version_downloads.downloads)");
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/krate/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub fn summary(req: &mut dyn RequestExt) -> EndpointResult {
.limit(10)
.load(&*conn)?
.into_iter()
.map(Keyword::encodable)
.map(Keyword::into)
.collect();

let popular_categories = Category::toplevel(&conn, "crates", 10, 0)?
Expand Down Expand Up @@ -178,7 +178,7 @@ pub fn show(req: &mut dyn RequestExt) -> EndpointResult {
.into_iter()
.map(|(v, pb, aas)| v.encodable(&krate.name, pb, aas))
.collect(),
keywords: kws.into_iter().map(Keyword::encodable).collect(),
keywords: kws.into_iter().map(Keyword::into).collect(),
categories: cats.into_iter().map(Category::into).collect(),
}))
}
Expand Down
10 changes: 3 additions & 7 deletions src/controllers/krate/owners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@ pub fn owners(req: &mut dyn RequestExt) -> EndpointResult {
let crate_name = &req.params()["crate_id"];
let conn = req.db_conn()?;
let krate: Crate = Crate::by_name(crate_name).first(&*conn)?;
let owners = krate
.owners(&conn)?
.into_iter()
.map(Owner::encodable)
.collect();
let owners = krate.owners(&conn)?.into_iter().map(Owner::into).collect();

#[derive(Serialize)]
struct R {
Expand All @@ -29,7 +25,7 @@ pub fn owner_team(req: &mut dyn RequestExt) -> EndpointResult {
let krate: Crate = Crate::by_name(crate_name).first(&*conn)?;
let owners = Team::owning(&krate, &conn)?
.into_iter()
.map(Owner::encodable)
.map(Owner::into)
.collect();

#[derive(Serialize)]
Expand All @@ -46,7 +42,7 @@ pub fn owner_user(req: &mut dyn RequestExt) -> EndpointResult {
let krate: Crate = Crate::by_name(crate_name).first(&*conn)?;
let owners = User::owning(&krate, &conn)?
.into_iter()
.map(Owner::encodable)
.map(Owner::into)
.collect();

#[derive(Serialize)]
Expand Down
4 changes: 1 addition & 3 deletions src/controllers/team.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,5 @@ pub fn show_team(req: &mut dyn RequestExt) -> EndpointResult {
struct R {
team: EncodableTeam,
}
Ok(req.json(&R {
team: team.encodable(),
}))
Ok(req.json(&R { team: team.into() }))
}
2 changes: 1 addition & 1 deletion src/controllers/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ pub fn new(req: &mut dyn RequestExt) -> EndpointResult {
api_token: EncodableApiTokenWithToken,
}
Ok(req.json(&R {
api_token: api_token.encodable_with_token(),
api_token: api_token.into(),
}))
}

Expand Down
4 changes: 1 addition & 3 deletions src/controllers/user/other.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ pub fn show(req: &mut dyn RequestExt) -> EndpointResult {
struct R {
user: EncodablePublicUser,
}
Ok(req.json(&R {
user: user.encodable_public(),
}))
Ok(req.json(&R { user: user.into() }))
}

/// Handles the `GET /users/:user_id/stats` route.
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/version/downloads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ pub fn downloads(req: &mut dyn RequestExt) -> EndpointResult {
.order(version_downloads::date)
.load(&*conn)?
.into_iter()
.map(VersionDownload::encodable)
.map(VersionDownload::into)
.collect();

#[derive(Serialize)]
Expand Down
9 changes: 0 additions & 9 deletions src/models/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use diesel::prelude::*;

use crate::models::Version;
use crate::schema::version_downloads;
use crate::views::EncodableVersionDownload;

#[derive(Queryable, Identifiable, Associations, Debug, Clone, Copy)]
#[belongs_to(Version)]
Expand Down Expand Up @@ -31,12 +30,4 @@ impl VersionDownload {
.execute(conn)?;
Ok(())
}

pub fn encodable(self) -> EncodableVersionDownload {
EncodableVersionDownload {
version: self.version_id,
downloads: self.downloads,
date: self.date.to_string(),
}
}
}
16 changes: 0 additions & 16 deletions src/models/keyword.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use diesel::prelude::*;

use crate::models::Crate;
use crate::schema::*;
use crate::views::EncodableKeyword;

#[derive(Clone, Identifiable, Queryable, Debug)]
pub struct Keyword {
Expand Down Expand Up @@ -61,21 +60,6 @@ impl Keyword {
&& name.chars().all(|c| c.is_ascii())
}

pub fn encodable(self) -> EncodableKeyword {
let Keyword {
crates_cnt,
keyword,
created_at,
..
} = self;
EncodableKeyword {
id: keyword.clone(),
created_at,
crates_cnt,
keyword,
}
}

pub fn update_crate(conn: &PgConnection, krate: &Crate, keywords: &[&str]) -> QueryResult<()> {
conn.transaction(|| {
let keywords = Keyword::find_or_create_all(conn, keywords)?;
Expand Down
41 changes: 0 additions & 41 deletions src/models/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ use diesel::pg::Pg;
use diesel::prelude::*;

use crate::app::App;
use crate::github;
use crate::util::errors::{cargo_err, AppResult};

use crate::models::{Crate, Team, User};
use crate::schema::{crate_owners, users};
use crate::views::EncodableOwner;

#[derive(Insertable, Associations, Identifiable, Debug, Clone, Copy)]
#[belongs_to(Crate)]
Expand Down Expand Up @@ -100,43 +98,4 @@ impl Owner {
Owner::Team(ref team) => team.id,
}
}

pub fn encodable(self) -> EncodableOwner {
match self {
Owner::User(User {
id,
name,
gh_login,
gh_avatar,
..
}) => {
let url = format!("https://github.com/{}", gh_login);
EncodableOwner {
id,
login: gh_login,
avatar: gh_avatar,
url: Some(url),
name,
kind: String::from("user"),
}
}
Owner::Team(Team {
id,
name,
login,
avatar,
..
}) => {
let url = github::team_url(&login);
EncodableOwner {
id,
login,
url: Some(url),
avatar,
name,
kind: String::from("team"),
}
}
}
}
}
22 changes: 1 addition & 21 deletions src/models/team.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use diesel::prelude::*;

use crate::app::App;
use crate::github::{github_api, team_url};
use crate::github::github_api;
use crate::util::errors::{cargo_err, AppResult, NotFound};

use oauth2::AccessToken;

use crate::models::{Crate, CrateOwner, Owner, OwnerKind, User};
use crate::schema::{crate_owners, teams};
use crate::views::EncodableTeam;

/// For now, just a Github Team. Can be upgraded to other teams
/// later if desirable.
Expand Down Expand Up @@ -213,25 +212,6 @@ impl Team {

Ok(teams.collect())
}

pub fn encodable(self) -> EncodableTeam {
let Team {
id,
name,
login,
avatar,
..
} = self;
let url = team_url(&login);

EncodableTeam {
id,
login,
name,
avatar,
url: Some(url),
}
}
}

fn team_with_gh_id_contains_user(
Expand Down
17 changes: 1 addition & 16 deletions src/models/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::models::User;
use crate::schema::api_tokens;
use crate::util::errors::{AppResult, InsecurelyGeneratedTokenRevoked};
use crate::util::rfc3339;
use crate::views::EncodableApiTokenWithToken;

const TOKEN_LENGTH: usize = 32;
const TOKEN_PREFIX: &str = "cio"; // Crates.IO
Expand Down Expand Up @@ -83,21 +82,6 @@ pub struct CreatedApiToken {
pub plaintext: String,
}

impl CreatedApiToken {
/// Converts this `CreatedApiToken` into an `EncodableApiToken` including
/// the actual token value for JSON serialization.
pub fn encodable_with_token(self) -> EncodableApiTokenWithToken {
EncodableApiTokenWithToken {
id: self.model.id,
name: self.model.name,
token: self.plaintext,
revoked: self.model.revoked,
created_at: self.model.created_at,
last_used_at: self.model.last_used_at,
}
}
}

// Use a custom implementation of Debug to hide the plaintext token.
impl std::fmt::Debug for CreatedApiToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Expand All @@ -111,6 +95,7 @@ impl std::fmt::Debug for CreatedApiToken {
#[cfg(test)]
mod tests {
use super::*;
use crate::views::EncodableApiTokenWithToken;
use chrono::NaiveDate;

#[test]
Expand Down
21 changes: 1 addition & 20 deletions src/models/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::util::errors::AppResult;

use crate::models::{ApiToken, Crate, CrateOwner, Email, NewEmail, Owner, OwnerKind, Rights};
use crate::schema::{crate_owners, emails, users};
use crate::views::{EncodablePrivateUser, EncodablePublicUser};
use crate::views::EncodablePrivateUser;

/// The model representing a row in the `users` database table.
#[derive(Clone, Debug, PartialEq, Eq, Queryable, Identifiable, AsChangeset, Associations)]
Expand Down Expand Up @@ -203,23 +203,4 @@ impl User {
.first(&*conn)
.optional()?)
}

/// Converts this`User` model into an `EncodablePublicUser` for JSON serialization.
pub fn encodable_public(self) -> EncodablePublicUser {
let User {
id,
name,
gh_login,
gh_avatar,
..
} = self;
let url = format!("https://github.com/{}", gh_login);
EncodablePublicUser {
id,
avatar: gh_avatar,
login: gh_login,
name,
url: Some(url),
}
}
}
4 changes: 2 additions & 2 deletions src/models/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,12 @@ impl Version {
authors: format!("/api/v1/crates/{}/{}/authors", crate_name, num),
},
crate_size,
published_by: published_by.map(User::encodable_public),
published_by: published_by.map(User::into),
audit_actions: audit_actions
.into_iter()
.map(|(audit_action, user)| EncodableAuditAction {
action: audit_action.action.into(),
user: User::encodable_public(user),
user: user.into(),
time: audit_action.time,
})
.collect(),
Expand Down
Loading