Skip to content

Commit

Permalink
Attempt to fix the relays projection in a generic way.
Browse files Browse the repository at this point in the history
  • Loading branch information
matteius committed Oct 6, 2024
1 parent 0af5ce2 commit 7dbb95c
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions opensensor/collection_apis.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from fastapi_pagination.default import Params as BaseParams
from fief_client import FiefUserInfo
from pydantic import BaseModel
from pydantic.fields import ModelField

from opensensor.collections import (
CO2,
Expand Down Expand Up @@ -197,9 +198,19 @@ def get_nested_fields(model: Type[BaseModel]) -> Dict[str, Type[BaseModel]]:
return nested_fields


def is_list_of_models(field: ModelField) -> bool:
if field.shape != 2: # 2 represents a list shape in Pydantic
return False
args = field.sub_fields[0].type_.__args__
return args and is_pydantic_model(args[0])


def get_list_item_type(field: ModelField) -> Type[BaseModel]:
return field.sub_fields[0].type_.__args__[0]


def create_nested_pipeline(model: Type[BaseModel], prefix=""):
logger.debug(f"Creating nested pipeline for model: {model.__name__}, prefix: {prefix}")
nested_fields = get_nested_fields(model)
match_conditions = {}
pipeline = {
"timestamp": "$timestamp",
Expand All @@ -218,24 +229,13 @@ def create_nested_pipeline(model: Type[BaseModel], prefix=""):
unit_field_name = f"{prefix}{mongo_field}_unit"
pipeline["unit"] = f"${unit_field_name}"
match_conditions[unit_field_name] = {"$exists": True}
elif field_name in nested_fields:
nested_type = nested_fields[field_name]
if get_origin(field.type_) is List:
# Handle array of nested objects
nested_pipeline, nested_match = create_nested_pipeline(nested_type, "")
pipeline[field_name] = {
"$map": {
"input": f"${full_mongo_field_name}",
"as": "item",
"in": nested_pipeline,
}
}
match_conditions[full_mongo_field_name] = {"$exists": True, "$ne": []}
else:
# Handle nested object
nested_pipeline, nested_match = create_nested_pipeline(nested_type, "")
pipeline[field_name] = nested_pipeline
match_conditions.update({f"{field_name}.{k}": v for k, v in nested_match.items()})
elif is_list_of_models(field):
item_model = get_list_item_type(field)
nested_pipeline, nested_match = create_nested_pipeline(item_model, "")
pipeline[field_name] = {
"$map": {"input": f"${full_mongo_field_name}", "as": "item", "in": nested_pipeline}
}
match_conditions[full_mongo_field_name] = {"$exists": True, "$ne": []}
else:
# Handle simple field
pipeline[field_name] = f"${full_mongo_field_name}"
Expand Down

0 comments on commit 7dbb95c

Please sign in to comment.