Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add expand-flag to RelationalBone #905

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 18 additions & 13 deletions src/viur/core/bones/relational.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ def __init__(
self,
*,
consistency: RelationalConsistency = RelationalConsistency.Ignore,
expand: bool = False,
format: str = "$(dest.name)",
kind: str = None,
module: Optional[str] = None,
Expand Down Expand Up @@ -194,7 +195,10 @@ def __init__(
Otherwise its n:1, (you can only select exactly one). It's possible to use a unique constraint on this
bone, allowing for at-most-1:1 or at-most-1:n relations. Instead of true, it's also possible to use
a :class:MultipleConstraints instead.

:param expand:
If True, allows for specific renders to expand the values of this relational bone to its full skeleton,
and not only the specified refKeys. This is useful to directly fetch entire data structures with just
one request, and is useful for modern single-page-apps.
:param format: Hint for the frontend how to display such an relation. This is now a python expression
evaluated by safeeval on the client side. The following values will be passed to the expression

Expand Down Expand Up @@ -253,6 +257,7 @@ def __init__(
"""
super().__init__(**kwargs)
self.format = format
self.expand = expand

if kind:
self.kind = kind
Expand Down Expand Up @@ -291,9 +296,7 @@ def __init__(
self.consistency = consistency

if getSystemInitialized():
from viur.core.skeleton import RefSkel, SkeletonInstance
self._refSkelCache = RefSkel.fromSkel(self.kind, *self.refKeys)
self._skeletonInstanceClassRef = SkeletonInstance
self.setSystemInitialized()

def setSystemInitialized(self):
"""
Expand All @@ -306,13 +309,9 @@ def setSystemInitialized(self):
:rtype: None
"""
super().setSystemInitialized()
from viur.core.skeleton import RefSkel, SkeletonInstance
self._refSkelCache = RefSkel.fromSkel(self.kind, *self.refKeys)
self._skeletonInstanceClassRef = SkeletonInstance

# from viur.core.skeleton import RefSkel, skeletonByKind
# self._refSkelCache = RefSkel.fromSkel(skeletonByKind(self.kind), *self.refKeys)
# self._usingSkelCache = self.using() if self.using else None
from viur.core import skeleton
self._refSkelCache = skeleton.RefSkel.fromSkel(self.kind, *self.refKeys) # FIXME: Rename this stupid name!
self._skeletonInstanceClassRef = skeleton.SkeletonInstance # FIXME: WTF????????

def _getSkels(self):
"""
Expand Down Expand Up @@ -1324,10 +1323,16 @@ def getUniquePropertyIndexValues(self, valuesCache: dict, name: str) -> List[str
return self._hashValueForUniquePropertyIndex([x["dest"]["key"] for x in value])

def structure(self) -> dict:
if self.expand:
from viur.core import skeleton
dest_skel = skeleton.skeletonByKind(self.kind)()
else:
dest_skel = self._refSkelCache()

return super().structure() | {
"type": f"{self.type}.{self.kind}",
"module": self.module,
"format": self.format,
"using": self.using().structure() if self.using else None,
"relskel": self._refSkelCache().structure(),
"using": self.using().structure() if self.using else None, # FIXME: Rename, see #647
"relskel": dest_skel.structure(), # FIXME: Rename, see #647
}
2 changes: 2 additions & 0 deletions src/viur/core/render/html/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@ def get_label(value) -> str:
return KeyValueWrapper(boneValue, get_label(boneValue))

elif bone.type == "relational" or bone.type.startswith("relational."):
# FIXME: Here, the RelationalBone.expand feature could be implemented,
# FIXME: in case this ugly, outdated piece of renderer is entirely refactored before.
if isinstance(boneValue, list):
tmpList = []
for k in boneValue:
Expand Down
30 changes: 20 additions & 10 deletions src/viur/core/render/json/default.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
from enum import Enum

from viur.core import bones, utils, db, current
from viur.core import bones, utils, db, current, skeleton
from viur.core.skeleton import SkeletonInstance
from viur.core.i18n import translate
from viur.core.config import conf
Expand Down Expand Up @@ -85,19 +85,29 @@ def renderSingleBoneValue(self, value: Any,
:return: A dict containing the rendered attributes.
"""
if isinstance(bone, bones.RelationalBone):
if isinstance(value, dict):
return {
"dest": self.renderSkelValues(value["dest"], injectDownloadURL=isinstance(bone, bones.FileBone)),
"rel": (self.renderSkelValues(value["rel"], injectDownloadURL=isinstance(bone, bones.FileBone))
if value["rel"] else None),
}
if not isinstance(value, dict):
return None # FIXME: Shall I raise?

dest = value["dest"]
rel = value["rel"]

if bone.expand:
skel = skeleton.skeletonByKind(bone.kind)()
if not skel.fromDB(dest["key"]):
return None # FIXME: Shall I raise?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, of course! Otherwise there wouldn't be a difference between no and invalid data!


dest = skel

return {
"dest": self.renderSkelValues(dest, injectDownloadURL=isinstance(bone, bones.FileBone)),
"rel": self.renderSkelValues(rel, injectDownloadURL=isinstance(bone, bones.FileBone)) if rel else None,
}
elif isinstance(bone, bones.RecordBone):
return self.renderSkelValues(value)
elif isinstance(bone, bones.PasswordBone):
return ""
else:
return value
return None

return value

def renderBoneValue(self, bone: bones.BaseBone, skel: SkeletonInstance, key: str) -> Union[List, Dict, None]:
boneVal = skel[key]
Expand Down