Skip to content

Commit

Permalink
services: add nested links context function
Browse files Browse the repository at this point in the history
  • Loading branch information
slint committed Apr 8, 2024
1 parent 8a8e856 commit 81533f4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
29 changes: 23 additions & 6 deletions invenio_records_resources/services/base/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from copy import deepcopy

from flask import current_app
from invenio_records.dictutils import dict_lookup, dict_set
from invenio_records.dictutils import dict_lookup
from uritemplate import URITemplate
from werkzeug.datastructures import MultiDict

Expand Down Expand Up @@ -97,20 +97,37 @@ def expand(self, identity, obj):
class NestedLinkGeneratorBase:
"""Base class for generating nested links."""

def __init__(self, tpl, key):
def __init__(self, links, key, context_func=None):
"""Initialize NestedLinkGenerator."""
self.tpl = tpl
self.links = links
self.key = key
self.context_func = context_func

def context(self, identity, record, key, value):
"""Get the context for the links."""
if not self.context_func:
return {}
return self.context_func(identity, record, key, value)


class NestedDictLinkGenerator(NestedLinkGeneratorBase):
"""Nested link generator for nested dictionaries."""

def update(self, identity, data, record):
"""Update data with links in each object inside the dictionary."""
for key, rf in operator.attrgetter(self.key)(record).items():
links = LinksTemplate(self.tpl, context={"id": rf.id}).expand(identity, rf)
dict_lookup(data, self.key)[key]["links"] = links
try:
nested_data = operator.attrgetter(self.key)(record)
if not isinstance(nested_data, dict):
return
for key, value in nested_data.items():
context = self.context(identity, record, key, value)
links = LinksTemplate(self.links, context=context).expand(
identity,
value,
)
dict_lookup(data, self.key)[key]["links"] = links
except AttributeError:
pass


class Link:
Expand Down
2 changes: 1 addition & 1 deletion invenio_records_resources/services/records/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def read(self, identity, id_, expand=False, action="read"):
record,
links_tpl=self.links_item_tpl,
expandable_fields=self.expandable_fields,
nested_links=self.config.nested_links,
nested_links=getattr(self.config, "nested_links", None),
expand=expand,
)

Expand Down

0 comments on commit 81533f4

Please sign in to comment.