JSON API > Pagination
OverviewJSON APIPagination
Pagination

The Lana TypeScript/JavaScript core library offers pagination helper functions that facilitate fetching items in a paginated manner. You can access these functions through the import path: @lana-commerce/core/json/fetchAllItems. There are two exported functions:

  • fetchAllItems - This function fetches all items at once. You need to provide the request constructor as an argument. It's important to set the sort_by parameter. The limit parameter is optional and will default to a predefined value if not specified.

    Here's an example of how you can use it:

    Example usage:

    // Import the necessary functions
    import { prettyPrintResponseError, request } from "@lana-commerce/core/json/commerce";
    import { fetchAllItems } from "@lana-commerce/core/json/fetchAllItems";
    
    // 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
      .sort_by("created_at"); // Specify the sorting parameter
    
    // Fetch all items
    const result = await fetchAllItems(req);
    
    // If the result doesn't contain data, throw an error
    if (result.kind !== "data") {
      throw new Error(prettyPrintResponseError(result));
    }
    
    // Print the id and title of each product
    for (const p of result.data) {
      console.log(`id: ${p.id}, title: ${p.title}`);
    }
    
  • iterAllItems - This function returns an asynchronous iterator over all items. As with fetchAllItems, you need to provide the request constructor as an argument, specifying the sort_by parameter and optionally the limit. If anything goes wrong, the function will throw an IterError.

    Example usage:

    // Import the necessary functions
    import { request } from "@lana-commerce/core/json/commerce";
    import { iterAllItems } from "@lana-commerce/core/json/fetchAllItems";
    // 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
      .sort_by("created_at"); // Specify the sorting parameter
    // Use the async iterator to go through all items
    for await (const p of iterAllItems(req)) {
      console.log(`id: ${p.id}, title: ${p.title}`);
    }
    

In both examples, the products are sorted by their creation time and are limited to 10 products per page.

PREVIOUS
Tutorial
NEXT
Expandable Items