Skip to content

Commit c0a0882

Browse files
committed
Backend: fix API error if lookup of Product or SalesOrder by id/sku doesn't yield any results
1 parent 5ab6f94 commit c0a0882

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

Backend/cosmic_works/cosmic_works_ai_agent.py

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -176,20 +176,35 @@ def get_single_item_by_field_name(
176176
"name": "@value",
177177
"value": field_value
178178
}
179-
]
180-
item = list(container.query_items(
179+
]
180+
items = list(container.query_items(
181181
query=query,
182182
parameters=parameters,
183183
enable_cross_partition_query=True
184-
))[0]
185-
item_casted = model(**item)
184+
))
185+
186+
# Check if any item is returned
187+
if not items:
188+
return None # Return None if no item is found
189+
190+
# Cast the item to the provided model
191+
item_casted = model(**items[0])
186192
return item_casted
193+
# item = list(container.query_items(
194+
# query=query,
195+
# parameters=parameters,
196+
# enable_cross_partition_query=True
197+
# ))[0]
198+
# item_casted = model(**item)
199+
# return item_casted
187200

188201
def get_product_by_id(product_id: str) -> str:
189202
"""
190203
Retrieves a product by its ID.
191204
"""
192205
item = get_single_item_by_field_name(product_v_container, "id", product_id, Product)
206+
if item is None:
207+
return json.dumps({"error": "Product with 'id' ({id}) not found."}, indent=4)
193208
delete_attribute_by_alias(item, "contentVector")
194209
return json.dumps(item, indent=4, default=str)
195210

@@ -198,6 +213,8 @@ def get_product_by_sku(sku: str) -> str:
198213
Retrieves a product by its sku.
199214
"""
200215
item = get_single_item_by_field_name(product_v_container, "sku", sku, Product)
216+
if item is None:
217+
return json.dumps({"error": "Product with 'sku' ({sku}) not found."}, indent=4)
201218
delete_attribute_by_alias(item, "contentVector")
202219
return json.dumps(item, indent=4, default=str)
203220

@@ -206,4 +223,6 @@ def get_sales_by_id(sales_id: str) -> str:
206223
Retrieves a sales order by its ID.
207224
"""
208225
item = get_single_item_by_field_name(sales_order_container, "id", sales_id, SalesOrder)
226+
if item is None:
227+
return json.dumps({"error": "SalesOrder with 'id' ({id}) not found."}, indent=4)
209228
return json.dumps(item, indent=4, default=str)

0 commit comments

Comments
 (0)