Skip to content

Commit

Permalink
feat: get contact by id
Browse files Browse the repository at this point in the history
I found this

https://github.com/thebracket/webinar_axumcrud

and I'm very happy about it
  • Loading branch information
jasonribble committed Jul 14, 2024
1 parent 55aebb3 commit 031463b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub trait ContactRepo {
async fn save_contact(&self, contact: models::Contact) -> anyhow::Result<i64>;
async fn get_all(&self) -> anyhow::Result<Vec<models::IndexedContact>>;
async fn update_contact(&self, update: models::ContactBuilder) -> anyhow::Result<()>;
async fn get_by_id(&self, id: i64) -> anyhow::Result<models::IndexedContact>;
}

pub struct PostgresContactRepo {
Expand Down Expand Up @@ -82,6 +83,18 @@ impl ContactRepo for PostgresContactRepo {

Ok(())
}

async fn get_by_id(&self, id: i64) -> anyhow::Result<models::IndexedContact> {
let query_get_by_id = "SELECT * FROM contacts WHERE id=$1";

let contact: models::IndexedContact =
sqlx::query_as::<_, models::IndexedContact>(query_get_by_id)
.bind(id)
.fetch_one(&*self.pg_pool)
.await?;

Ok(contact)
}
}

#[cfg(test)]
Expand Down Expand Up @@ -144,4 +157,29 @@ mod tests {

assert!(result.is_ok());
}

#[tokio::test]
async fn test_get_contact_by_id() {
let mut mock_contact_repo = MockContactRepo::new();

let contact = models::IndexedContact {
id: 1,
contact: models::Contact::new("John", "Doe", "[email protected]", "1234567890")
.unwrap(),
};

mock_contact_repo
.expect_get_by_id()
.times(1)
.with(eq(contact.id))
.return_once(|_| Ok(contact));

let result = mock_contact_repo.get_by_id(1).await;

assert!(result.is_ok());

let actual_contact = result.unwrap();

assert_eq!(actual_contact.id, 1);
}
}
4 changes: 4 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ async fn main() -> anyhow::Result<()> {

let _ = contact_repo.update_contact(edits).await;

let my_first_contact = contact_repo.get_by_id(1).await.unwrap();

println!("My first contact is {my_first_contact:?}");

Ok(())
}

Expand Down

0 comments on commit 031463b

Please sign in to comment.