Skip to content

Commit

Permalink
views: fix non container resources returned an empty dict
Browse files Browse the repository at this point in the history
A separate view is required for non-container resources, and the container view takes out keys on the current object and only keeps the children.

Closes #53
  • Loading branch information
robvdl committed Mar 16, 2024
1 parent 905bcd5 commit 804be88
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions src/sambal/views/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,37 @@ def flatten(resource: Resource) -> dict:
This can't easily be done at the Resource level otherwise it stops
traversal completely.
Filter out children of containers to stop it returning nested containers.
"""
# Filter children of containers to stop it returning infinite nested data.
if isinstance(resource, ContainerResource):
return {k: obj for k, obj in resource.items() if not isinstance(obj, Resource)}

return resource


@view_config(context=Resource, permission="read", renderer="json")
@view_config(context=ContainerResource, permission="read", renderer="json")
@view_config(context=RootFactory, permission="read", renderer="json")
def resource_view(context, request):
"""Temporary view to produce JSON for every node.
def container_view(context, request):
"""View for containers and the roof factory which is also a container.
For this to work a custom JSON encoder is used to deal with the
various objects that aren't JSON encode-able out of the box.
First of all filtering out anything but Resource takes out the keys that
are on the container itself. These can be retrieved from the parent.
Secondly, flatten removes any nested containers. Right now this is only
an issue for the RootFactory, but it could also be in some containers.
Without flatten it ends up returning endless nested data.
This could otherwise make responses too big for larger domains.
"""
return {k: flatten(obj) for k, obj in context.items() if isinstance(obj, Resource)}


@view_config(context=Resource, permission="read", renderer="json")
def resource_view(context, request):
"""View to produce JSON for non-container resources.
This returns data on the current node and doesn't need to worry about
children as there won't be any.
"""
return context

0 comments on commit 804be88

Please sign in to comment.