Get contact #10

Merged
phoenix merged 6 commits from get_contact into main 2026-06-14 23:25:35 -04:00
8 changed files with 353 additions and 129 deletions
+5
View File
@@ -5,6 +5,11 @@ on:
branches:
- main
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
name: Check
Generated
+1 -1
View File
@@ -2293,7 +2293,7 @@ dependencies = [
[[package]]
name = "textsender_api"
version = "0.1.5"
version = "0.1.6"
dependencies = [
"axum",
"axum-extra",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "textsender_api"
version = "0.1.5"
version = "0.1.6"
edition = "2024"
rust-version = "1.96"
+198
View File
@@ -0,0 +1,198 @@
pub mod request {
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Debug, Deserialize, Serialize, ToSchema)]
pub struct AddContactRequest {
pub phone_number: String,
pub firstname: Option<String>,
pub lastname: Option<String>,
pub nickname: Option<String>,
pub user_id: uuid::Uuid,
}
impl AddContactRequest {
pub fn is_valid(&self) -> bool {
!self.phone_number.is_empty() || !self.user_id.is_nil()
}
}
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct GetContactParams {
pub id: Option<uuid::Uuid>,
pub user_id: Option<uuid::Uuid>,
}
}
pub mod response {
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
pub struct AddContactResponse {
pub message: String,
pub data: Vec<textsender_models::contact::Contact>,
}
pub use AddContactResponse as GetContactResponse;
/*
#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
pub struct GetContactResponse {
pub message: String,
pub data: Vec<textsender_models::contact::Contact>,
}
*/
}
pub mod endpoint {
// use axum::{Json, response::IntoResponse};
use crate::repo::contact as contact_repo;
/// Endpoint to create Contact
#[utoipa::path(
post,
path = super::super::endpoints::ADD_CONTACT,
request_body(
content = super::request::AddContactRequest,
description = "Data needed to create a Contact",
content_type = "application/json"
),
responses(
(status = 201, description = "Contact created", body = super::response::AddContactResponse),
(status = 400, description = "Error", body = super::response::AddContactResponse),
(status = 500, description = "Error creating Contact", body = super::response::AddContactResponse)
)
)]
pub async fn create_contact(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::AddContactRequest>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::AddContactResponse>,
) {
let mut response = super::response::AddContactResponse::default();
if payload.is_valid() {
match contact_repo::get_with_user_id_and_phone(
&pool,
&payload.user_id,
&payload.phone_number,
)
.await
{
Ok(_) => {
println!("Already created");
response.message = String::from("Already created");
(axum::http::StatusCode::NOT_MODIFIED, axum::Json(response))
}
Err(err) => {
match err {
sqlx::Error::RowNotFound => {
println!("Good to create");
// Put code here
let mut contact = textsender_models::contact::Contact {
firstname: payload.firstname,
lastname: payload.lastname,
phone_number: payload.phone_number,
nickname: payload.nickname,
user_id: Some(payload.user_id),
..Default::default()
};
match contact_repo::insert(&pool, &contact).await {
Ok(id) => {
contact.id = Some(id);
response.message =
String::from(super::super::response::SUCCESSFUL);
response.data.push(contact);
(axum::http::StatusCode::CREATED, axum::Json(response))
}
Err(err) => {
eprintln!("Error: {err:?}");
response.message = String::from("Contact not created");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
_ => {
eprintln!("Error: {err:?}");
response.message = String::from("Something went wrong");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
}
} else {
response.message = String::from("Request body is not valid");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
// Endpoint to get songs
#[utoipa::path(
get,
path = super::super::endpoints::GET_CONTACT,
params(
("id" = uuid::Uuid, Path, description = "Id of Contact"),
("user_id" = uuid::Uuid, Path, description = "User Id associated with the Contact")
),
responses(
(status = 200, description = "Songs found", body = super::response::GetContactResponse),
(status = 400, description = "Error getting songs", body = super::response::GetContactResponse)
)
)]
pub async fn get_contacts(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Query(params): axum::extract::Query<super::request::GetContactParams>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::GetContactResponse>,
) {
let mut response = super::response::GetContactResponse::default();
let contacts = match params.id {
Some(id) => match contact_repo::get(&pool, &id).await {
Ok(contact) => {
vec![contact]
}
Err(err) => {
eprintln!("Error: {err:?}");
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
);
}
},
None => match params.user_id {
Some(user_id) => match contact_repo::get_with_user_id(&pool, &user_id).await {
Ok(contacts) => contacts,
Err(err) => {
eprintln!("Error: {err:?}");
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
);
}
},
None => {
response.message = String::from("Invalid parameter");
return (axum::http::StatusCode::BAD_REQUEST, axum::Json(response));
}
},
};
response.data = contacts;
response.message = String::from(super::super::response::SUCCESSFUL);
(axum::http::StatusCode::OK, axum::Json(response))
}
}
+4 -126
View File
@@ -1,8 +1,12 @@
pub mod contact;
pub mod endpoints {
pub const ROOT: &str = "/";
/// Constant for adding Contact endpoint
pub const ADD_CONTACT: &str = "/api/v1/contact/new";
/// Constant for getting Contact endpoint
pub const GET_CONTACT: &str = "/api/v1/contact";
}
pub mod response {
@@ -13,129 +17,3 @@ pub mod response {
pub async fn root() -> &'static str {
"Hello, World!"
}
pub mod contact {
pub mod request {
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Debug, Deserialize, Serialize, ToSchema)]
pub struct AddContactRequest {
pub phone_number: String,
pub firstname: Option<String>,
pub lastname: Option<String>,
pub nickname: Option<String>,
pub user_id: uuid::Uuid,
}
impl AddContactRequest {
pub fn is_valid(&self) -> bool {
!self.phone_number.is_empty() || !self.user_id.is_nil()
}
}
}
pub mod response {
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Debug, Default, Deserialize, Serialize, ToSchema)]
pub struct AddContactResponse {
pub message: String,
pub data: Vec<textsender_models::contact::Contact>,
}
}
pub mod endpoint {
// use axum::{Json, response::IntoResponse};
use crate::repo::contact as contact_repo;
/// Endpoint to create Contact
#[utoipa::path(
post,
path = super::super::endpoints::ADD_CONTACT,
request_body(
content = super::request::AddContactRequest,
description = "Data needed to create a Contact",
content_type = "application/json"
),
responses(
(status = 201, description = "Contact created", body = super::response::AddContactResponse),
(status = 400, description = "Error", body = super::response::AddContactResponse),
(status = 500, description = "Error creating Contact", body = super::response::AddContactResponse)
)
)]
pub async fn create_contact(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::AddContactRequest>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::AddContactResponse>,
) {
let mut response = super::response::AddContactResponse::default();
if payload.is_valid() {
match contact_repo::get_with_user_id_and_phone(
&pool,
&payload.user_id,
&payload.phone_number,
)
.await
{
Ok(_) => {
println!("Already created");
response.message = String::from("Already created");
(axum::http::StatusCode::NOT_MODIFIED, axum::Json(response))
}
Err(err) => {
match err {
sqlx::Error::RowNotFound => {
println!("Good to create");
// Put code here
let mut contact = textsender_models::contact::Contact {
firstname: payload.firstname,
lastname: payload.lastname,
phone_number: payload.phone_number,
nickname: payload.nickname,
user_id: Some(payload.user_id),
..Default::default()
};
match contact_repo::insert(&pool, &contact).await {
Ok(id) => {
contact.id = Some(id);
response.message =
String::from(super::super::response::SUCCESSFUL);
response.data.push(contact);
(axum::http::StatusCode::CREATED, axum::Json(response))
}
Err(err) => {
eprintln!("Error: {err:?}");
response.message = String::from("Contact not created");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
_ => {
eprintln!("Error: {err:?}");
response.message = String::from("Something went wrong");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
}
} else {
response.message = String::from("Request body is not valid");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
}
+7 -1
View File
@@ -10,7 +10,7 @@ pub mod host {
pub mod init {
use std::time::Duration;
use axum::routing::post;
use axum::routing::{get, post};
use tower_http::timeout::TimeoutLayer;
use utoipa::OpenApi;
@@ -89,6 +89,12 @@ pub mod init {
crate::auth::auth::<axum::body::Body>,
)),
)
.route(
crate::caller::endpoints::GET_CONTACT,
get(contact_endpoints::get_contacts).route_layer(axum::middleware::from_fn(
crate::auth::auth::<axum::body::Body>,
)),
)
.layer(cors::configure_cors().await)
}
+58
View File
@@ -119,4 +119,62 @@ pub mod contact {
},
}
}
pub async fn get_with_user_id(
pool: &sqlx::PgPool,
user_id: &uuid::Uuid,
) -> Result<Vec<textsender_models::contact::Contact>, sqlx::Error> {
match sqlx::query(
r#"
SELECT id, firstname, lastname, nickname, phone_number, user_id FROM "contacts"
WHERE
user_id = $1;
"#,
)
.bind(user_id)
.fetch_all(pool)
.await
{
Ok(rows) => {
let mut contacts: Vec<textsender_models::contact::Contact> = Vec::new();
for row in rows {
let id: uuid::Uuid = row.try_get("id")?;
let phone_number: String = row.try_get("phone_number")?;
let user_id: uuid::Uuid = row.try_get("user_id")?;
let contact = textsender_models::contact::Contact {
id: Some(id),
firstname: match row.try_get("firstname") {
Ok(val) => val,
Err(err) => {
eprintln!("Error: {err:?}");
None
}
},
lastname: match row.try_get("lastname") {
Ok(val) => val,
Err(err) => {
eprintln!("Error: {err:?}");
None
}
},
nickname: match row.try_get("nickname") {
Ok(val) => val,
Err(err) => {
eprintln!(
"Error: nickname has no value for contacts record {err:?}"
);
None
}
},
phone_number,
user_id: Some(user_id),
};
contacts.push(contact);
}
Ok(contacts)
}
Err(_) => Err(sqlx::Error::RowNotFound),
}
}
}
+79
View File
@@ -188,6 +188,30 @@ mod request {
.unwrap();
app.clone().oneshot(req).await
}
pub async fn get_contact(
app: &axum::Router,
id: &uuid::Uuid,
) -> Result<axum::response::Response, std::convert::Infallible> {
let uri = format!(
"{}?id={}",
textsender_api::caller::endpoints::GET_CONTACT,
id
);
let req = axum::http::Request::builder()
.method(axum::http::Method::GET)
.uri(uri)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.header(
axum::http::header::AUTHORIZATION,
super::bearer_auth().await,
)
.body(axum::body::Body::empty())
.unwrap();
app.clone().oneshot(req).await
}
}
/// Test contact phone number
@@ -228,3 +252,58 @@ async fn test_create_contact() {
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
}
#[tokio::test]
async fn test_get_contact() {
let tm_pool = db_mgr::get_pool().await.unwrap();
let db_name = db_mgr::generate_db_name().await;
match db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
}
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
db::migrations(&pool).await;
let app = init::app(pool).await;
// Send request
match request::create_contact(&app).await {
Ok(response) => {
let resp = util::get_resp_data::<
textsender_api::caller::contact::response::AddContactResponse,
>(response)
.await;
assert_eq!(false, resp.data.is_empty(), "Should not be empty");
let contact = &resp.data[0];
assert_eq!(true, contact.id.is_some(), "Missing Contact Id");
let id = contact.id.unwrap();
match request::get_contact(&app, &id).await {
Ok(response) => {
let resp = util::get_resp_data::<
textsender_api::caller::contact::response::GetContactResponse,
>(response)
.await;
assert_eq!(
false,
resp.data.is_empty(),
"At least Contact record should have been returned"
);
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {:?}", err);
}
};
let _ = db_mgr::drop_database(&tm_pool, &db_name).await;
}