Skip to content

Commit d9c3709

Browse files
committed
controllers/version: Add a helper trait to simplify validation
1 parent 837c67b commit d9c3709

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

Diff for: src/controllers/version.rs

+20-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use utoipa::IntoParams;
1515

1616
use crate::models::{Crate, Version};
1717
use crate::schema::{crates, versions};
18-
use crate::util::errors::{AppResult, crate_not_found, version_not_found};
18+
use crate::util::errors::AppResult;
1919

2020
#[derive(Deserialize, FromRequestParts, IntoParams)]
2121
#[into_params(parameter_in = Path)]
@@ -54,9 +54,7 @@ async fn version_and_crate(
5454
.first(conn)
5555
.await
5656
.optional()?
57-
.ok_or_else(|| crate_not_found(crate_name))?;
58-
59-
let version = version.ok_or_else(|| version_not_found(crate_name, semver))?;
57+
.gather(crate_name, semver)?;
6058
Ok((version, krate))
6159
}
6260

@@ -68,6 +66,7 @@ fn deserialize_version<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Str
6866

6967
mod ext {
7068
use super::*;
69+
use crate::util::errors::{crate_not_found, version_not_found};
7170
use crates_io_diesel_helpers::canon_crate_name;
7271

7372
#[diesel::dsl::auto_type()]
@@ -90,4 +89,21 @@ mod ext {
9089
crate_and_version_query(&self.name, &self.version)
9190
}
9291
}
92+
93+
pub trait CrateVersionHelper<C, V> {
94+
fn gather(self, crate_name: &str, semver: &str) -> AppResult<(C, V)>;
95+
fn gather_from_path(self, path: &CrateVersionPath) -> AppResult<(C, V)>;
96+
}
97+
98+
impl<C, V> CrateVersionHelper<C, V> for Option<(C, Option<V>)> {
99+
fn gather(self, crate_name: &str, semver: &str) -> AppResult<(C, V)> {
100+
let (krate, version) = self.ok_or_else(|| crate_not_found(crate_name))?;
101+
let version = version.ok_or_else(|| version_not_found(crate_name, semver))?;
102+
Ok((krate, version))
103+
}
104+
105+
fn gather_from_path(self, path: &CrateVersionPath) -> AppResult<(C, V)> {
106+
self.gather(&path.name, &path.version)
107+
}
108+
}
93109
}

0 commit comments

Comments
 (0)