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.
-
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 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
-
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 benull
). - If expasion is requested, the value has a type of
T | null
. On successful expansion it will beT
, if expansion failed or the item was null to begin with, it will benull
.
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 typeT
. Otherwise, it could be of typeT
,{ id: string }
, ornull
. - If expansion is not requested,