Files
openapi-first/openapi_first/templates/crud_app/data.py

133 lines
2.8 KiB
Python

"""
In-memory mock data store for CRUD example.
This module intentionally avoids persistence and concurrency guarantees.
It is suitable for demos, tests, and scaffolding only.
It intentionally avoids
- persistence
- concurrency guarantees
- validation
- error handling
The implementation is suitable for:
- demonstrations
- tests
- scaffolding and example services
It is explicitly NOT suitable for production use.
This module is not part of the ``openapi_first`` library API surface.
"""
from typing import Dict
# In-memory storage keyed by item ID.
_items: Dict[int, dict] = {
1: {"id": 1, "name": "Apple", "price": 0.5},
2: {"id": 2, "name": "Banana", "price": 0.3},
}
# Auto-incrementing ID counter.
_next_id = 3
def list_items() -> list[dict]:
"""
Return all items in the data store.
This function performs no filtering, pagination, or sorting.
The returned collection reflects the current in-memory state.
Returns
-------
list[dict]
A list of item representations.
"""
return list(_items.values())
def get_item(item_id: int) -> dict:
"""
Retrieve a single item by ID.
This function assumes the item exists and will raise ``KeyError``
if the ID is not present in the store.
Parameters
----------
item_id : int
Identifier of the item to retrieve.
Returns
-------
dict
The stored item representation.
"""
return _items[item_id]
def create_item(payload: dict) -> dict:
"""
Create a new item in the data store.
A new integer ID is assigned automatically. No validation is
performed on the provided payload.
Parameters
----------
payload : dict
Item attributes excluding the ``id`` field.
Returns
-------
dict
The newly created item, including its assigned ID.
"""
global _next_id
item = {"id": _next_id, **payload}
_items[_next_id] = item
_next_id += 1
return item
def update_item(item_id: int, payload: dict) -> dict:
"""
Replace an existing item in the data store.
This function overwrites the existing item entirely and does not
perform partial updates or validation. If the item does not exist,
it will be created implicitly.
Parameters
----------
item_id : int
Identifier of the item to update.
payload : dict
Item attributes excluding the ``id`` field.
Returns
-------
dict
The updated item representation.
"""
item = {"id": item_id, **payload}
_items[item_id] = item
return item
def delete_item(item_id: int):
"""
Remove an item from the data store.
This function assumes the item exists and will raise ``KeyError``
if the ID is not present.
Parameters
----------
item_id : int
Identifier of the item to delete.
"""
del _items[item_id]