Skip to content

Commit

Permalink
replace GCP Firestore asdict with Model core version
Browse files Browse the repository at this point in the history
  • Loading branch information
douwevandermeij committed Aug 4, 2022
1 parent 42d1f2e commit 28d304b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 13 deletions.
2 changes: 1 addition & 1 deletion fractal/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Fractal is a scaffolding toolkit for building SOLID logic for your Python applications."""

__version__ = "0.4.13"
__version__ = "0.4.14"

from abc import ABC

Expand Down
24 changes: 12 additions & 12 deletions fractal/contrib/gcp/firestore/repositories.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from dataclasses import asdict
from datetime import date
from decimal import Decimal
from typing import Iterator, Optional

from google.cloud import firestore
Expand Down Expand Up @@ -107,28 +105,30 @@ def is_healthy(self) -> bool:
return True


class FirestoreDict(dict):
def __init__(self, obj):
for i, v in enumerate(obj):
if type(v[1]) is Decimal:
obj[i] = (v[0], f"{v[1]:.2f}")
if type(v[1]) is date:
obj[i] = (v[0], v[1].isoformat())
super(FirestoreDict, self).__init__(obj)
# class FirestoreDict(dict):
# def __init__(self, obj):
# for i, v in enumerate(obj):
# if type(v[1]) is Decimal:
# obj[i] = (v[0], f"{v[1]:.2f}")
# if type(v[1]) is date:
# obj[i] = (v[0], v[1].isoformat())
# super(FirestoreDict, self).__init__(obj)


class FirestoreRepositoryDictMixin(FirestoreRepositoryMixin[Entity]):
def add(self, entity: Entity) -> Entity:
doc_ref = self.collection.document(entity.id)
doc_ref.set(asdict(entity, dict_factory=FirestoreDict))
# doc_ref.set(asdict(entity, dict_factory=FirestoreDict))
doc_ref.set(entity.asdict())
return entity

def update(self, entity: Entity, *, upsert=False) -> Entity:
if not upsert:
doc_ref = self.collection.document(entity.id)
doc = doc_ref.get()
if doc.exists:
doc_ref.set(asdict(entity, dict_factory=FirestoreDict))
# doc_ref.set(asdict(entity, dict_factory=FirestoreDict))
doc_ref.set(entity.asdict())
return entity
return self.add(entity)

Expand Down
6 changes: 6 additions & 0 deletions fractal/core/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from dataclasses import asdict, dataclass, fields
from datetime import date
from decimal import Decimal
from enum import Enum
from typing import Dict

Expand Down Expand Up @@ -29,6 +31,10 @@ def _asdict(v):
return v.asdict()
elif isinstance(v, list):
return [_asdict(i) for i in v]
elif isinstance(v, Decimal):
return f"{v:.2f}"
elif isinstance(v, date):
return v.isoformat()
return v

ret = {k: _asdict(v) for k, v in self.__dict__.items() if k in field_names}
Expand Down

0 comments on commit 28d304b

Please sign in to comment.