Skip to content

Commit e6d45a9

Browse files
committed
Merge pull request #222 from Turbo87/simplify
Two small code simplifications
2 parents 5e0f3bc + 892872c commit e6d45a9

File tree

4 files changed

+10
-9
lines changed

4 files changed

+10
-9
lines changed

src/keyword.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,9 +159,7 @@ pub fn index(req: &mut Request) -> CargoResult<Response> {
159159
}
160160

161161
// Query for the total count of keywords
162-
let stmt = try!(conn.prepare("SELECT COUNT(*) FROM keywords"));
163-
let row = try!(stmt.query(&[])).into_iter().next().unwrap();
164-
let total = row.get(0);
162+
let total = try!(Keyword::count(conn));
165163

166164
#[derive(RustcEncodable)]
167165
struct R { keywords: Vec<EncodableKeyword>, meta: Meta }

src/krate.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -588,11 +588,7 @@ pub fn index(req: &mut Request) -> CargoResult<Response> {
588588
/// Handles the `GET /summary` route.
589589
pub fn summary(req: &mut Request) -> CargoResult<Response> {
590590
let tx = try!(req.tx());
591-
let num_crates = {
592-
let stmt = try!(tx.prepare("SELECT COUNT(*) FROM crates"));
593-
let rows = try!(stmt.query(&[]));
594-
rows.iter().next().unwrap().get("count")
595-
};
591+
let num_crates = try!(Crate::count(tx));
596592
let num_downloads = {
597593
let stmt = try!(tx.prepare("SELECT total_downloads FROM metadata"));
598594
let rows = try!(stmt.query(&[]));

src/model.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,11 @@ pub trait Model: Sized {
1616
let row = try!(rows.into_iter().next().chain_error(|| NotFound));
1717
Ok(Model::from_row(&row))
1818
}
19+
20+
fn count(conn: &GenericConnection) -> CargoResult<i64> {
21+
let sql = format!("SELECT COUNT(*) FROM {}", Model::table_name(None::<Self>));
22+
let stmt = try!(conn.prepare(&sql));
23+
let rows = try!(stmt.query(&[]));
24+
Ok(rows.iter().next().unwrap().get("count"))
25+
}
1926
}

src/user/middleware.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,11 @@ impl conduit_middleware::Middleware for Middleware {
3232
None => {
3333

3434
// Look for an `Authorization` header on the request
35-
let tx = try!(req.tx().map_err(std_error));
3635
match req.headers().find("Authorization") {
3736
Some(headers) => {
3837

3938
// Look for a user in the database with a matching API token
39+
let tx = try!(req.tx().map_err(std_error));
4040
match User::find_by_api_token(tx, &headers[0]) {
4141
Ok(user) => user,
4242
Err(..) => return Ok(())

0 commit comments

Comments
 (0)