RedHatInsights / mocks

Mock services for testing cloud.redhat.com applications
4 stars 10 forks source link

Create pagination helper #8

Open bsquizz opened 3 years ago

bsquizz commented 3 years ago

We might need a more thorough pagination implementation to generate paginated responses.

I was looking around to see if there was anything that would make generating a paginated response from a simple list of data easy and so far the most promising I found is flask-paginate but we'd need to tweak it because it is designed more with generating a quick page UI in mind. There's an example here:

https://gist.github.com/mozillazg/69fb40067ae6d80386e10e105e6803c9

Using the RBAC mock as an example, I think in our case this could translate to something like:

from flask_paginate import Pagination, get_page_args

def get_permissions(identity, application, offset=0, limit=10):
    # do stuff to get the identity/look up stored permissions in tinydb here
    total = len(permissions)
    return total, permissions[offset: offset + limit]

@blueprint.route("/v1/access/", methods=["GET"])
def rbac_access():
    page, per_page, offset = get_page_args(page_parameter='page', per_page_parameter='limit')
    total, paginated_permissions = get_permissions(identity, application, offset, limit)
    pagination = Pagination(page=page, per_page=per_page, total=total)
    rbac_response = deepcopy(BASE_RBAC_RESPONSE)
    rbac_response["data"] = [{"resourceDefinitions": [], "permission": perm} for perm in paginated_permissions]
    rbac_response["meta"]["count"] = total
    rbac_response["meta"]["limit"] = per_page
    rbac_response["meta"]["offset"] = offset
    # need a way to generate link URLs ...
    '''
    rbac_response["links"]["first"] = 
    rbac_response["links"]["next"] = 
    rbac_response["links"]["previous"] = 
    rbac_response["links"]["last"] = 
    '''

The problem is the Pagination class currently doesn't offer a way to get just the plain URL from the first_page/next_page/last_page/prev_page: https://github.com/lixxu/flask-paginate/blob/master/flask_paginate/__init__.py#L439-L470

It returns some formatted HTML. We could open a PR to add functions that allow us to get just the plain URL string: https://github.com/lixxu/flask-paginate/blob/master/flask_paginate/__init__.py#L451