miLibris / flask-rest-jsonapi

Flask extension to build REST APIs around JSONAPI 1.0 specification.
http://flask-rest-jsonapi.readthedocs.io
MIT License
597 stars 153 forks source link

Filter relationships in backend #106

Closed etiennecaldo closed 6 years ago

etiennecaldo commented 6 years ago

Hi everyone, Thank you for the great work here. I have been using this framework smoothly in production app for few months. My question today is: how could I achieve a filter relationships in backend to hide some data. I know I can change the query for the base object but what about the relationships that are serialized?

I mean, for example a User is part of two projects and one of them is "secret" (that means only Admin may view it).

What I would like to do is:

I know how to differentiate Admin from User but after that, how could I filter the relationships before they are serialized?

Solution 1:

Solution 2:

Do you have any other idea? Thanks in advance for your help...!

etiennecaldo commented 6 years ago

Ok I found a solution: I overloaded the fields.Relationship class from marshmallow-jsonapi like this:

class ConditionalRelationship(Relationship):
    def __init__(self, filterValueFunc, *args, **kwargs):
        super(ConditionalRelationship, self).__init__(*args, **kwargs)
        self.filterValueFunc = filterValueFunc

    def _serialize(self, value, attr, obj):
        value = self.filterValueFunc(value, attr, obj)
        return super(ConditionalRelationship, self)._serialize(value, attr, obj)

and I do my logic in filterValueFunc, given as an input.