diff options
| author | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2025-10-23 22:06:01 +0200 |
|---|---|---|
| committer | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2025-10-23 22:06:01 +0200 |
| commit | 1a7f887451faee3083f5bbf55979665a4e6bc7f4 (patch) | |
| tree | ba8c78f52495de25810777f880881761122feef5 /crates | |
| parent | chore(crates/rocie-client): Re-generate (diff) | |
| download | server-1a7f887451faee3083f5bbf55979665a4e6bc7f4.zip | |
feat(crates/rocie-server/api/get-product-{by-name,by-part-name}): Init
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/rocie-client/README.md | 4 | ||||
| -rw-r--r-- | crates/rocie-client/docs/ApiGetProductApi.md | 60 | ||||
| -rw-r--r-- | crates/rocie-client/src/apis/api_get_product_api.rs | 91 | ||||
| -rw-r--r-- | crates/rocie-server/src/api/get/mod.rs | 2 | ||||
| -rw-r--r-- | crates/rocie-server/src/api/get/product.rs | 55 | ||||
| -rw-r--r-- | crates/rocie-server/src/main.rs | 2 | ||||
| -rw-r--r-- | crates/rocie-server/src/storage/sql/get/product/mod.rs | 25 | ||||
| -rw-r--r-- | crates/rocie-server/src/storage/sql/product.rs | 2 |
8 files changed, 236 insertions, 5 deletions
diff --git a/crates/rocie-client/README.md b/crates/rocie-client/README.md index c01f023..54e918e 100644 --- a/crates/rocie-client/README.md +++ b/crates/rocie-client/README.md @@ -27,7 +27,9 @@ All URIs are relative to *http://localhost* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *ApiGetInventoryApi* | [**amount_by_id**](docs/ApiGetInventoryApi.md#amount_by_id) | **GET** /inventory/{id} | Get the amount of an product -*ApiGetProductApi* | [**product_by_id**](docs/ApiGetProductApi.md#product_by_id) | **GET** /product/{id} | Get Product by id +*ApiGetProductApi* | [**product_by_id**](docs/ApiGetProductApi.md#product_by_id) | **GET** /product/by-id/{id} | Get Product by id +*ApiGetProductApi* | [**product_by_name**](docs/ApiGetProductApi.md#product_by_name) | **GET** /product/by-name/{name} | Get Product by name +*ApiGetProductApi* | [**product_suggestion_by_name**](docs/ApiGetProductApi.md#product_suggestion_by_name) | **GET** /product/by-part-name/{name} | Get Product suggestion by name *ApiGetProductApi* | [**products**](docs/ApiGetProductApi.md#products) | **GET** /products/ | Return all registered products *ApiGetUnitApi* | [**unit_by_id**](docs/ApiGetUnitApi.md#unit_by_id) | **GET** /unit/{id} | Get Unit by id *ApiGetUnitApi* | [**units**](docs/ApiGetUnitApi.md#units) | **GET** /units/ | Return all registered units diff --git a/crates/rocie-client/docs/ApiGetProductApi.md b/crates/rocie-client/docs/ApiGetProductApi.md index bc991c5..a7d0918 100644 --- a/crates/rocie-client/docs/ApiGetProductApi.md +++ b/crates/rocie-client/docs/ApiGetProductApi.md @@ -4,7 +4,9 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- -[**product_by_id**](ApiGetProductApi.md#product_by_id) | **GET** /product/{id} | Get Product by id +[**product_by_id**](ApiGetProductApi.md#product_by_id) | **GET** /product/by-id/{id} | Get Product by id +[**product_by_name**](ApiGetProductApi.md#product_by_name) | **GET** /product/by-name/{name} | Get Product by name +[**product_suggestion_by_name**](ApiGetProductApi.md#product_suggestion_by_name) | **GET** /product/by-part-name/{name} | Get Product suggestion by name [**products**](ApiGetProductApi.md#products) | **GET** /products/ | Return all registered products @@ -37,6 +39,62 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +## product_by_name + +> models::Product product_by_name(name) +Get Product by name + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**name** | **String** | Name of the product | [required] | + +### Return type + +[**models::Product**](Product.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +## product_suggestion_by_name + +> Vec<models::Product> product_suggestion_by_name(name) +Get Product suggestion by name + +### Parameters + + +Name | Type | Description | Required | Notes +------------- | ------------- | ------------- | ------------- | ------------- +**name** | **String** | Partial name of a product | [required] | + +### Return type + +[**Vec<models::Product>**](Product.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json, text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + ## products > Vec<models::Product> products() diff --git a/crates/rocie-client/src/apis/api_get_product_api.rs b/crates/rocie-client/src/apis/api_get_product_api.rs index 481084b..2e18d8a 100644 --- a/crates/rocie-client/src/apis/api_get_product_api.rs +++ b/crates/rocie-client/src/apis/api_get_product_api.rs @@ -24,6 +24,23 @@ pub enum ProductByIdError { UnknownValue(serde_json::Value), } +/// struct for typed errors of method [`product_by_name`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ProductByNameError { + Status404(), + Status500(String), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`product_suggestion_by_name`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ProductSuggestionByNameError { + Status500(String), + UnknownValue(serde_json::Value), +} + /// struct for typed errors of method [`products`] #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] @@ -37,7 +54,7 @@ pub async fn product_by_id(configuration: &configuration::Configuration, id: mod // add a prefix to parameters to efficiently prevent name collisions let p_id = id; - let uri_str = format!("{}/product/{id}", configuration.base_path, id=p_id.to_string()); + let uri_str = format!("{}/product/by-id/{id}", configuration.base_path, id=p_id.to_string()); let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); if let Some(ref user_agent) = configuration.user_agent { @@ -69,6 +86,78 @@ pub async fn product_by_id(configuration: &configuration::Configuration, id: mod } } +pub async fn product_by_name(configuration: &configuration::Configuration, name: &str) -> Result<models::Product, Error<ProductByNameError>> { + // add a prefix to parameters to efficiently prevent name collisions + let p_name = name; + + let uri_str = format!("{}/product/by-name/{name}", configuration.base_path, name=crate::apis::urlencode(p_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::Product`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::Product`")))), + } + } else { + let content = resp.text().await?; + let entity: Option<ProductByNameError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + +pub async fn product_suggestion_by_name(configuration: &configuration::Configuration, name: &str) -> Result<Vec<models::Product>, Error<ProductSuggestionByNameError>> { + // add a prefix to parameters to efficiently prevent name collisions + let p_name = name; + + let uri_str = format!("{}/product/by-part-name/{name}", configuration.base_path, name=crate::apis::urlencode(p_name)); + let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str); + + if let Some(ref user_agent) = configuration.user_agent { + req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + } + + let req = req_builder.build()?; + let resp = configuration.client.execute(req).await?; + + let status = resp.status(); + let content_type = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("application/octet-stream"); + let content_type = super::ContentType::from(content_type); + + if !status.is_client_error() && !status.is_server_error() { + let content = resp.text().await?; + match content_type { + ContentType::Json => serde_json::from_str(&content).map_err(Error::from), + ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec<models::Product>`"))), + ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec<models::Product>`")))), + } + } else { + let content = resp.text().await?; + let entity: Option<ProductSuggestionByNameError> = serde_json::from_str(&content).ok(); + Err(Error::ResponseError(ResponseContent { status, content, entity })) + } +} + pub async fn products(configuration: &configuration::Configuration, ) -> Result<Vec<models::Product>, Error<ProductsError>> { let uri_str = format!("{}/products/", configuration.base_path); diff --git a/crates/rocie-server/src/api/get/mod.rs b/crates/rocie-server/src/api/get/mod.rs index e21a120..1c32105 100644 --- a/crates/rocie-server/src/api/get/mod.rs +++ b/crates/rocie-server/src/api/get/mod.rs @@ -7,6 +7,8 @@ pub(crate) mod unit_property; pub(crate) fn register_paths(cfg: &mut web::ServiceConfig) { cfg.service(product::product_by_id) + .service(product::product_by_name) + .service(product::product_suggestion_by_name) .service(product::products) .service(unit::units) .service(unit::unit_by_id) diff --git a/crates/rocie-server/src/api/get/product.rs b/crates/rocie-server/src/api/get/product.rs index 90cb8c8..9356a68 100644 --- a/crates/rocie-server/src/api/get/product.rs +++ b/crates/rocie-server/src/api/get/product.rs @@ -16,7 +16,7 @@ use crate::{ ("id" = ProductId, description = "Product id" ), ) )] -#[get("/product/{id}")] +#[get("/product/by-id/{id}")] pub(crate) async fn product_by_id( app: web::Data<App>, id: web::Path<ProductIdStub>, @@ -29,6 +29,59 @@ pub(crate) async fn product_by_id( } } +/// Get Product by name +#[utoipa::path( + responses( + (status = OK, description = "Product found from database", body = Product), + (status = NOT_FOUND, description = "Product not found in database"), + (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) + ), + params( + ("name" = String, description = "Name of the product" ), + ) +)] +// TODO: Html decode the name, before use. Otherwise `Milk 2` will not work, as it is send as +// `Milk+2` <2025-10-21> +#[get("/product/by-name/{name}")] +pub(crate) async fn product_by_name( + app: web::Data<App>, + name: web::Path<String>, +) -> Result<impl Responder> { + let name = name.into_inner(); + + match Product::from_name(&app, name).await? { + Some(product) => Ok(HttpResponse::Ok().json(product)), + None => Ok(HttpResponse::NotFound().finish()), + } +} + +/// Get Product suggestion by name +#[utoipa::path( + responses( + (status = OK, description = "Product suggestions found from database", body = Vec<Product>), + (status = INTERNAL_SERVER_ERROR, description = "Server encountered error", body = String) + ), + params( + ("name" = String, description = "Partial name of a product" ), + ) +)] +#[get("/product/by-part-name/{name}")] +pub(crate) async fn product_suggestion_by_name( + app: web::Data<App>, + name: web::Path<String>, +) -> Result<impl Responder> { + let name = name.into_inner(); + + let all = Product::get_all(&app).await?; + + let matching = all + .into_iter() + .filter(|product| product.name.starts_with(name.as_str())) + .collect::<Vec<_>>(); + + Ok(HttpResponse::Ok().json(matching)) +} + /// Return all registered products #[utoipa::path( responses( diff --git a/crates/rocie-server/src/main.rs b/crates/rocie-server/src/main.rs index 8e10763..2329b0b 100644 --- a/crates/rocie-server/src/main.rs +++ b/crates/rocie-server/src/main.rs @@ -20,6 +20,8 @@ async fn main() -> Result<(), std::io::Error> { #[openapi( paths( api::get::product::product_by_id, + api::get::product::product_by_name, + api::get::product::product_suggestion_by_name, api::get::product::products, api::get::unit::units, api::get::unit::unit_by_id, diff --git a/crates/rocie-server/src/storage/sql/get/product/mod.rs b/crates/rocie-server/src/storage/sql/get/product/mod.rs index 01047b2..0df51d8 100644 --- a/crates/rocie-server/src/storage/sql/get/product/mod.rs +++ b/crates/rocie-server/src/storage/sql/get/product/mod.rs @@ -36,6 +36,31 @@ impl Product { } } + pub(crate) async fn from_name(app: &App, name: String) -> Result<Option<Self>, from_id::Error> { + let record = query!( + " + SELECT name, id, unit_property, description, parent + FROM products + WHERE name = ? +", + name + ) + .fetch_optional(&app.db) + .await?; + + if let Some(record) = record { + Ok(Some(Self { + id: ProductId::from_db(&record.id), + unit_property: UnitPropertyId::from_db(&record.unit_property), + name, + description: record.description, + associated_bar_codes: vec![], // todo + })) + } else { + Ok(None) + } + } + pub(crate) async fn get_all(app: &App) -> Result<Vec<Self>, get_all::Error> { let records = query!( " diff --git a/crates/rocie-server/src/storage/sql/product.rs b/crates/rocie-server/src/storage/sql/product.rs index 2575b59..1c5a7d8 100644 --- a/crates/rocie-server/src/storage/sql/product.rs +++ b/crates/rocie-server/src/storage/sql/product.rs @@ -20,7 +20,7 @@ pub(crate) struct Product { /// The name of the product. /// /// This should be globally unique, to make searching easier for the user. - pub(super) name: String, + pub(crate) name: String, /// An optional description of this product. pub(super) description: Option<String>, |
