torchbox / wagtail-headless-preview

Previews for headless Wagtail setups

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

DX: Simplify fetching previews.

dopry opened this issue · comments

Current wagtail-headless-preview adds a class method get_page_from_preview_token via the HeadlessPreviewMixin. However when calling from Generic client code developers don't necessarily know what class they need to call this method on, so they need to identify this class. Leading to code like

  id = params.get("id")
    if id:
        page = WagtailPage.objects.get(pk=id).specific
        if page:
            page_type = type(page)
            if hasattr(page_type, "get_page_from_preview_token"):
                return page_type.get_page_from_preview_token(token)

    content_type = params.get("page_type")
    if content_type:
        app_label, model = content_type.lower().split(".")
        ctype = ContentType.objects.get(app_label=app_label, model=model)
        if ctype:
            cls = ctype.model_class()
            if hasattr(cls, "get_page_from_preview_token"):
                return cls.get_page_from_preview_token(token)

Being required of every consumer of get_page_from_preview_token. It would nice if there were an exported function akin to

def get_page_preview_from_token(token):
    """
    Get a preview page from a token.
    """
    token_params_list = token.split(":").pop(0)
    token_params_kvstr = token_params_list.split(";")

    params = {}
    for arg in token_params_kvstr:
        key, value = arg.split("=")
        params[key] = value

    id = params.get("id")
    if id:
        page = WagtailPage.objects.get(pk=id).specific
        if page:
            page_type = type(page)
            if hasattr(page_type, "get_page_from_preview_token"):
                return page_type.get_page_from_preview_token(token)

    content_type = params.get("page_type")
    if content_type:
        app_label, model = content_type.lower().split(".")
        ctype = ContentType.objects.get(app_label=app_label, model=model)
        if ctype:
            cls = ctype.model_class()
            if hasattr(cls, "get_page_from_preview_token"):
                return cls.get_page_from_preview_token(token)

    return None

that would save consumers needing to implement the class lookup. Someone more familiar with headless preview might have better ideas to make this developer experience better, but this is what I'm proposing in wagtail grapple and what was easy for me to implement with my limited knowledge.