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

Tree viewset for retrieving nested, paginated views of topic trees #8138

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
34 changes: 21 additions & 13 deletions kolibri/core/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,15 @@ def remove_invalid_fields(self, queryset, fields, view, request):
return ordering


class ReadOnlyValuesViewset(viewsets.ReadOnlyModelViewSet):
class BaseValuesViewset(viewsets.GenericViewSet):
"""
A viewset that uses a values call to get all model/queryset data in
a single database query, rather than delegating serialization to a
DRF ModelSerializer.
"""

# A tuple of values to get from the queryset
values = None
# values = None
# A map of target_key, source_key where target_key is the final target_key that will be set
# and source_key is the key on the object retrieved from the values call.
# Alternatively, the source_key can be a callable that will be passed the object and return
Expand All @@ -134,8 +134,8 @@ class ReadOnlyValuesViewset(viewsets.ReadOnlyModelViewSet):
field_map = {}

def __init__(self, *args, **kwargs):
viewset = super(ReadOnlyValuesViewset, self).__init__(*args, **kwargs)
if not isinstance(self.values, tuple):
viewset = super(BaseValuesViewset, self).__init__(*args, **kwargs)
if not hasattr(self, "values") or not isinstance(self.values, tuple):
raise TypeError("values must be defined as a tuple")
self._values = tuple(self.values)
if not isinstance(self.field_map, dict):
Expand Down Expand Up @@ -205,6 +205,18 @@ def serialize(self, queryset):
list(map(self._map_fields, values_queryset or [])), queryset
)

def serialize_object(self, **filter_kwargs):
queryset = self.get_queryset()
try:
filter_kwargs = filter_kwargs or self._get_lookup_filter()
return self.serialize(queryset.filter(**filter_kwargs))[0]
except IndexError:
raise Http404(
"No %s matches the given query." % queryset.model._meta.object_name
)


class ListModelMixin(object):
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())

Expand All @@ -218,20 +230,16 @@ def list(self, request, *args, **kwargs):

return Response(self.serialize(queryset))

def serialize_object(self, **filter_kwargs):
queryset = self.get_queryset()
try:
filter_kwargs = filter_kwargs or self._get_lookup_filter()
return self.serialize(queryset.filter(**filter_kwargs))[0]
except IndexError:
raise Http404(
"No %s matches the given query." % queryset.model._meta.object_name
)

class RetrieveModelMixin(object):
def retrieve(self, request, *args, **kwargs):
return Response(self.serialize_object())


class ReadOnlyValuesViewset(BaseValuesViewset, RetrieveModelMixin, ListModelMixin):
pass


class CreateModelMixin(BaseCreateModelMixin):
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
Expand Down
50 changes: 50 additions & 0 deletions kolibri/core/assets/src/api-resources/contentNode.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import isPlainObject from 'lodash/isPlainObject';
import { Resource } from 'kolibri.lib.apiResource';
import Store from 'kolibri.coreVue.vuex.store';
import urls from 'kolibri.urls';
import cloneDeep from '../cloneDeep';

export default new Resource({
name: 'contentnode',
Expand Down Expand Up @@ -34,4 +37,51 @@ export default new Resource({
fetchNextSteps(getParams) {
return this.fetchDetailCollection('next_steps', Store.getters.currentUserId, getParams);
},
cache: {},
fetchModel({ id }) {
rtibbles marked this conversation as resolved.
Show resolved Hide resolved
if (this.cache[id]) {
return Promise.resolve(this.cache[id]);
}
return this.client({ url: this.modelUrl(id) }).then(response => {
this.cacheData(response.data);
return response.data;
});
},
cacheData(data) {
if (Array.isArray(data)) {
for (let model of data) {
this.cacheData(model);
}
} else if (isPlainObject(data)) {
if (data[this.idKey]) {
this.cache[data[this.idKey]] = Object.assign(
this.cache[data[this.idKey]] || {},
cloneDeep(data)
);
if (data.children) {
this.cacheData(data.children);
}
} else if (data.results) {
for (let model of data.results) {
this.cacheData(model);
}
}
}
},
fetchCollection(params) {
return this.client({ url: this.collectionUrl(), params }).then(response => {
this.cacheData(response.data);
return response.data;
});
},
fetchTree(id, params) {
const url = urls['kolibri:core:contentnode_tree_detail'](id);
return this.client({ url, params }).then(response => {
this.cacheData(response.data);
return response.data;
});
},
fetchMoreTree({ id, params }) {
rtibbles marked this conversation as resolved.
Show resolved Hide resolved
return this.fetchTree(id, params);
},
});
Loading