JSON API > Expandable Items
OverviewJSON APIExpandable Items
Expandable Items

The Lana API incorporates a concept known as "expandable items". With the Lana TypeScript/JavaScript core library, you can request the expansion of specific items in a returned request. This mini-tutorial will guide you through the process of working with expandable items.

  1. How to request item expansion?

    The Request API provides a type-safe expand() method that you can use to request item expansion. If you're using an Integrated Development Environment (IDE) with TypeScript support, you can utilize the IDE to list all possible expansions.

    expansion contextual help

    Expansion requests can be recursive. That is, you can expand items within an expandable item. In the following example, expansion of variants on a product page and media files within the variant are requested.

    // Import the necessary functions
    import { request } from "@lana-commerce/core/json/commerce";
    // Construct the request
    const req = request(ctx, "GET:products/page.json")
      .shop_id(ctx.shopID) // Set the shop ID
      .limit(10) // Set the limit for the number of items per page
      .expand({
        // Specify the items to expand
        "items.variants": {
          "media_files.file": true,
          "linked_media_files.file": true,
        },
      })
      .sort_by("created_at"); // Specify the sorting parameter
    
  2. How to work with expandable items?

    An expandable item is of the following type:

    type ExpandableItem<T> = T | { id: string } | null;
    
    • If expansion is not requested, { id: string } variant is always returned (unless item is logically optional, in which case it can also be null).
    • If expasion is requested, the value has a type of T | null. On successful expansion it will be T, if expansion failed or the item was null to begin with, it will be null.

    Lana TypeScript/JavaScript core library offers a helper which allows you to check if item was expanded or not. Example:

    // Import the necessary function
    import { isExpanded } from "@lana-commerce/core/json/commerce";
    // Check if the item is expanded
    if (isExpanded(item)) {
      // In this block, the item is of type T
    } else {
      // In this block, the item is of type T, { id: string } or null
    }
    

    In the above code, the isExpanded function is used to determine whether an item has been expanded or not. If the item is expanded, it's guaranteed to be of type T. Otherwise, it could be of type T, { id: string }, or null.

PREVIOUS
Pagination
NEXT
Lana UI