Skip to content

Commit

Permalink
Can fetch package data by name or ID
Browse files Browse the repository at this point in the history
  • Loading branch information
ericthelemur committed Oct 2, 2022
1 parent b3679fc commit 5e2bbe7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
13 changes: 13 additions & 0 deletions dcspkg-server/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@ pub async fn get_package_by_name(
Ok(all.pop())
}

pub async fn get_package_by_id(
conn: &mut PoolConnection<Sqlite>,
id: i64,
) -> Result<Option<Package>, sqlx::Error> {
let mut all: Vec<Package> = sqlx::query_as("SELECT * FROM packages WHERE id=?")
.bind(id)
.fetch_all(conn)
.await?;
//get latest version
all.sort_by_key(|p| semver::Version::parse(&p.version).unwrap());
Ok(all.pop())
}

pub async fn get_all_packages(
conn: &mut PoolConnection<Sqlite>,
) -> Result<Vec<Package>, sqlx::Error> {
Expand Down
11 changes: 7 additions & 4 deletions dcspkg-server/src/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::db::{get_all_packages, get_package_by_name, PackageDB};
use crate::db::{get_all_packages, get_package_by_name, get_package_by_id, PackageDB};
use dcspkg_common::Package;
use rocket::get;
use rocket::serde::json::Json;
Expand All @@ -14,8 +14,11 @@ pub async fn list(mut db: Connection<PackageDB>) -> Json<Vec<Package>> {

#[get("/pkgdata/<name>")]
pub async fn pkgdata(mut db: Connection<PackageDB>, name: &str) -> Option<Json<Package>> {
match get_package_by_name(&mut *db, name).await {
Ok(x) => x.map(Json),
Err(e) => panic!("{e:?}"), //TODO, work out how to handle failure in reponder
let mut pkg = get_package_by_name(&mut *db, name).await.ok()?;
// If nothing, attempt fetching by ID
if pkg.is_none() {
let id: i64 = name.parse().ok()?;
pkg = get_package_by_id(&mut *db, id).await.ok()?;
}
pkg.map(Json)
}

0 comments on commit 5e2bbe7

Please sign in to comment.