Skip to content

Commit c8a3d45

Browse files
committed
Leverage the project projection which handles units.
1 parent 435e1b1 commit c8a3d45

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

opensensor/collection_apis.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ def create_nested_pipeline(model: Type[BaseModel], prefix=""):
252252
return pipeline, match_conditions
253253

254254

255-
def create_model_instance(model: Type[BaseModel], data: dict):
255+
def create_model_instance(model: Type[BaseModel], data: dict, target_unit: Optional[str] = None):
256256
nested_fields = get_nested_fields(model)
257257

258258
for field_name, _ in model.__fields__.items():
@@ -272,7 +272,10 @@ def create_model_instance(model: Type[BaseModel], data: dict):
272272
if unit_field in data:
273273
data[field_name] = data[unit_field]
274274
continue
275-
# Check if the mongo_field exists in the data
275+
276+
# Handle temperature unit conversion if applicable
277+
if field_name == "temp" and target_unit and mongo_field in data:
278+
data[field_name] = convert_temperature(data[mongo_field], data.get("unit"), target_unit)
276279
elif mongo_field in data:
277280
data[field_name] = data[mongo_field]
278281
elif field_name in data:
@@ -293,10 +296,13 @@ def create_model_instance(model: Type[BaseModel], data: dict):
293296
if field_name in data:
294297
if isinstance(data[field_name], list):
295298
data[field_name] = [
296-
create_model_instance(nested_model, item) for item in data[field_name]
299+
create_model_instance(nested_model, item, target_unit)
300+
for item in data[field_name]
297301
]
298302
else:
299-
data[field_name] = create_model_instance(nested_model, data[field_name])
303+
data[field_name] = create_model_instance(
304+
nested_model, data[field_name], target_unit
305+
)
300306

301307
logger.debug(f"Creating instance of {model.__name__} with data: {data}")
302308
return model(**data)
@@ -501,10 +507,7 @@ def sample_and_paginate_collection(
501507
# So, you can directly use it to create the response model instances.
502508
data = [VPD(**item) for item in raw_data]
503509
else:
504-
data = [create_model_instance(response_model, item) for item in raw_data]
505-
if data and unit:
506-
for item in data:
507-
convert_temperature(item, unit)
510+
data = [create_model_instance(response_model, item, unit) for item in raw_data]
508511

509512
# Re-run for total page count
510513
pipeline.append({"$count": "total"})
@@ -535,8 +538,6 @@ async def historical_data_route(
535538

536539
# TODO - Refactor this to support paid collections
537540
collection_name = "FreeTier"
538-
if not isinstance(entity, Temperature):
539-
unit = None
540541

541542
return sample_and_paginate_collection(
542543
entity,

0 commit comments

Comments
 (0)