Router
This documentation details the DocumentStore class, an essential component for data persistence in your architecture, designed to offer flexibility and decoupling.
On this page
#Overview
The DocumentStore class acts as a Router and Proxy for NoSQL database operations. Its main goal is to abstract away which database is being used (MongoDB or Local JSON).
This allows developers to write the business logic code only once, and switch the storage just by changing an environment variable or an initial parameter, which is ideal for switching between Production (MongoDB) and Development/Testing (Local) environments.
#Execution Flow
The class follows a simple three-step logic:
- Instantiation: When the object is created, the code checks the
backendargument or theNOSQL_BACKENDenvironment variable. - Factory: The internal method
_initialize_managerdecides which manager class to instantiate (MongoDBManagerorLocalManager). - Delegation (Proxy): When a method such as
save_payloadis called,DocumentStoredoes not process the data directly; it "passes the ball" to the manager instantiated in step 2.
#Methods Table
| Method | Type | Brief Description |
|---|---|---|
__init__ | Constructor | Sets the backend and initializes the manager. |
_initialize_manager | Private | Decision logic (Factory) to choose the backend. |
save_payload | Proxy | Inserts new documents into the database. |
fetch_documents | Proxy | Searches and retrieves filtered documents. |
update_documents | Proxy | Updates data of existing documents. |
delete_documents | Proxy | Removes documents from the database. |
#Architecture and Insights
- Proxy Pattern: The class serves as a unified interface. The code that calls
DocumentStoredoes not need to know how MongoDB works, only what it wants to do. - Factory Pattern: The logic for creating the database object is centralized in a single place, making it easier to add new backends in the future (such as Redis or DynamoDB).
- Decoupling: The use of
argsand*kwargsin the methods allows the interface to be generic enough to accept the different parameters required by distinct backends without breaking the method signatures.
#Class Details
#DocumentStore Class
Description
A high-level abstraction class that manages the persistence of NoSQL documents. It centralizes CRUD (Create, Read, Update, Delete) operations and delegates execution to specific backends depending on the configuration.
Arguments
backend(Optional[str]): A string indicating the desired backend. Accepted values:"mongo"or"local". IfNone, it looks up theNOSQL_BACKENDenvironment variable.
#Methods
#1. _initialize_manager
Description
Internal method that decides which database implementation will be loaded into memory.
Arguments
- Has no direct arguments (uses the state of
self.backend).
Returns
Union[MongoDBManager, LocalManager]: An instance of the class responsible for the actual communication with the database.
Raises
ValueError: If the given backend is not "mongo" or "local".
#2. save_payload
Description
Inserts a document or data load into the selected backend.
Arguments
args/*kwargs: Usually include the database name, the collection/table name and the data dictionary (payload).
Returns
dict: Information about the success of the operation (e.g. ID of the inserted document).
Raises
Exception: Propagates errors specific to the database connection driver.
Examples
store = DocumentStore(backend="local")
store.save_payload(db="app", collection="logs", data={"status": "sucesso"})#3. fetch_documents
Description
Queries the database to return documents that match the given criteria.
Arguments
args/*kwargs: Search filters (e.g.{"id": 123}).
Returns
list: A list containing the documents found (dictionaries).
Examples
# Busca todos os usuários com nome Enzo
users = store.fetch_documents("mydb", "users", {"name": "Enzo"})#4. update_documents
Description
Modifies existing documents in the database based on a selection criterion.
Arguments
args/*kwargs: Search filter and the new data to be applied.
Returns
dict: Summary of the operation (number of fields changed).
Examples
store.update_documents("mydb", "users", {"name": "Enzo"}, {"active": True})#5. delete_documents
Description
Removes one or more documents from the database.
Arguments
args/*kwargs: Filters to identify which documents must be deleted.
Returns
dict: Confirmation of the removal.
Examples
store.delete_documents("mydb", "users", {"name": "Enzo"})#Use
import json
from src.database.no_relational_db.router import DocumentStore
manager = DocumentStore(backend="local")
manager.save_payload("mydb", "users", {"name": "Enzo"})
docs = manager.fetch_documents("mydb", "users", {"name": "Enzo"})
print(json.dumps(docs, indent=4))
manager.update_documents("mydb", "users", {"name": "Enzo"}, {"age": 25})
manager.delete_documents("mydb", "users", {"name": "Enzo"})
response = manager.save_payload("mydb", "users", {"name": "Enzo"})
print(response["inserted_id"])Source: src/database/no_relational_db/router.py