xStore.recommendations

Gợi ý sản phẩm và ghi nhận lượt xem. Hai hàm đọc trả về MẢNG TRẦN, không phải phong bì { items }.

Phương thức

Phương thức Cú pháp Mô tả Từ phiên bản
forProduct xStore.recommendations.forProduct(productId, { ruleType, limit }): Promise<ProductRecommendation[]> Sản phẩm gợi ý cho một sản phẩm cụ thể. Trả MẢNG TRẦN, và mỗi phần tử chỉ có id, title, slug, current_status — hydrate bằng products.list({ ids }) nếu cần giá và ảnh. 1.0
recentlyViewed xStore.recommendations.recentlyViewed({ customerId, sessionToken, limit }): Promise<ProductRecommendation[]> Sản phẩm khách vừa xem. Cũng là MẢNG TRẦN. Nhận diện khách bằng customerId khi đã đăng nhập, hoặc bằng sessionToken tự sinh cho khách vãng lai. 1.0
recordView xStore.recommendations.recordView({ productId, customerId?, sessionToken? }): Promise<void> Ghi nhận một lượt xem sản phẩm. 1.0

Ví dụ đầy đủ

<script>
  // Ghi nhận lượt xem ngay khi mở trang chi tiết — đây là dữ liệu nuôi
  // "sản phẩm đã xem" và các gợi ý theo hành vi.
  const productId = document.body.dataset.productId;   // ví dụ: 'k3n8fq2wla'

  xStore.recommendations.recordView({ productId });

  // Hai hàm đọc trả về MẢNG TRẦN (không có .items), và mỗi phần tử chỉ
  // có id, title, slug, current_status — KHÔNG có giá, ảnh hay url.
  // Muốn thẻ sản phẩm đầy đủ thì lấy id rồi hydrate một lần.
  async function renderRelated() {
    const goiY = await xStore.recommendations.forProduct(productId, { limit: 8 });
    if (goiY.length === 0) return;

    const the = await xStore.products.list({ ids: goiY.map((p) => p.id) });

    document.getElementById('related').innerHTML = the.items.map((p) => `
      <a class="product-card" href="${p.url ?? '#'}">
        <img src="${p.cover_image_url ?? ''}" alt="${p.title}" loading="lazy">
        <span>${p.title}</span>
        <span>${xStore.utils.formatCurrency(p.effective_price ?? p.price ?? 0)}</span>
      </a>
    `).join('');
  }

  async function renderRecentlyViewed() {
    const goiY = await xStore.recommendations.recentlyViewed({ limit: 6 });
    document.getElementById('recent').innerHTML =
      goiY.map((p) => `<span>${p.title}</span>`).join('');
  }

  renderRelated();
  renderRecentlyViewed();
</script>

Thư viện gọi tới /api/... trên chính tên miền cửa hàng, nên không cần khai báo địa chỉ máy chủ ở bất kỳ đâu.

Xem thêm Sự kiện để giao diện tự cập nhật sau mỗi thao tác.