@shopkit/data-layer 1.4.5 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -296,6 +296,16 @@ var BaseCommerceClient = class {
296
296
  getCollectionFilters(params, options) {
297
297
  this.throwNotImplemented("getCollectionFilters");
298
298
  }
299
+ /**
300
+ * Read a page of collections, with their products and variants, from one query document
301
+ * @param params - Query document (filter, fields, include, sort, paging)
302
+ * @param options - Request options (headers, timeout, etc.)
303
+ * @returns Promise resolving to collections, with paging in meta.pagination
304
+ * @throws NotImplementedError if not implemented in adapter
305
+ */
306
+ queryCollections(params, options) {
307
+ this.throwNotImplemented("queryCollections");
308
+ }
299
309
  // ========================================
300
310
  // ORDER OPERATIONS
301
311
  // ========================================
@@ -3735,6 +3745,11 @@ var BaseCustomService = class {
3735
3745
  `Request failed: ${response.status} ${response.statusText}`
3736
3746
  );
3737
3747
  error.status = response.status;
3748
+ try {
3749
+ error.body = await response.json();
3750
+ } catch {
3751
+ error.body = void 0;
3752
+ }
3738
3753
  throw error;
3739
3754
  }
3740
3755
  this.logger.info("API request successful", {
@@ -3775,6 +3790,9 @@ function mapGetCollectionsByHandelsResponse(response) {
3775
3790
  function mapGetCollectionFiltersResponse(response) {
3776
3791
  return response;
3777
3792
  }
3793
+ function mapQueryCollectionsResponse(response) {
3794
+ return response?.collections || [];
3795
+ }
3778
3796
 
3779
3797
  // src/adapters/custom/product/urls.ts
3780
3798
  var DEFAULT_VERSION = "v1";
@@ -3783,10 +3801,11 @@ var PRODUCT_ENDPOINTS = {
3783
3801
  getProduct: (v = DEFAULT_VERSION) => `/api/${v}/product/details`,
3784
3802
  getProductsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/product/details`,
3785
3803
  getCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections`,
3786
- getCollectionByHandle: (v = DEFAULT_VERSION, h) => `/api/${v}/collections/handle/${h}`,
3787
- getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${id}`,
3804
+ getCollectionByHandle: (v = DEFAULT_VERSION, h) => `/api/${v}/collections/handle/${encodeURIComponent(h)}`,
3805
+ getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${encodeURIComponent(id)}`,
3788
3806
  getCollectionsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/collections/details`,
3789
- getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${collectionHandle}/filters`
3807
+ getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${encodeURIComponent(collectionHandle)}/filters`,
3808
+ queryCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections/query`
3790
3809
  };
3791
3810
 
3792
3811
  // src/adapters/custom/product/service.ts
@@ -4363,7 +4382,123 @@ var ProductService2 = class extends BaseCustomService {
4363
4382
  });
4364
4383
  }
4365
4384
  }
4385
+ /**
4386
+ * Read a page of collections, with their products and variants, from one
4387
+ * query document. A POST because the document is too nested for a URL; it is
4388
+ * still a read and answers 200.
4389
+ */
4390
+ async queryCollections(params, options) {
4391
+ try {
4392
+ const payload = buildCollectionsQueryPayload(params);
4393
+ const handles = handlesNamedBy(payload.filter);
4394
+ const result = await this.request(
4395
+ PRODUCT_ENDPOINTS.queryCollections(options?.version),
4396
+ "POST",
4397
+ payload,
4398
+ {
4399
+ ...options || {},
4400
+ // Same coverage as the other collection reads: the broad tag for
4401
+ // catalog-wide purges, plus one per handle the filter names, so a
4402
+ // collection.updated / product.updated webhook reaches every page built
4403
+ // from this read. A filter that names no handle (published: true, a
4404
+ // $like, ...) cannot know its result set in advance — broad tag only.
4405
+ // No `revalidate`, as with getCollectionsByHandles.
4406
+ next: {
4407
+ ...options?.next || {},
4408
+ tags: [
4409
+ CacheTags.collections(),
4410
+ ...handles.map((h) => CacheTags.collection(h)),
4411
+ ...options?.next?.tags || []
4412
+ ]
4413
+ }
4414
+ }
4415
+ );
4416
+ const errors = Array.isArray(result?.errors) ? result.errors : [];
4417
+ if (!result?.data) {
4418
+ return formatResponse({
4419
+ success: false,
4420
+ message: "Collections query returned no data.",
4421
+ error: {
4422
+ code: "UPSTREAM_UNAVAILABLE",
4423
+ message: "No data in collections query response."
4424
+ },
4425
+ meta: { requestId: result?.request_id }
4426
+ });
4427
+ }
4428
+ return formatResponse({
4429
+ success: true,
4430
+ message: "Collections retrieved successfully.",
4431
+ data: mapQueryCollectionsResponse(result.data),
4432
+ meta: {
4433
+ pagination: result.data.paging,
4434
+ requestId: result.request_id,
4435
+ ...errors.length > 0 ? { errors } : {}
4436
+ }
4437
+ });
4438
+ } catch (error) {
4439
+ this.logger.error("Error in queryCollections", void 0, { error });
4440
+ const body = error?.body;
4441
+ if (isUpstreamUnavailable(error)) {
4442
+ return formatResponse({
4443
+ success: false,
4444
+ message: "An error occurred while processing the request.",
4445
+ error: {
4446
+ code: "UPSTREAM_UNAVAILABLE",
4447
+ message: typeof error?.status === "number" ? `Request failed: ${error.status}` : "Collections query did not complete."
4448
+ },
4449
+ meta: { requestId: body?.request_id }
4450
+ });
4451
+ }
4452
+ const upstreamErrors = Array.isArray(body?.errors) ? body.errors : [];
4453
+ return formatResponse({
4454
+ success: false,
4455
+ message: "The collections query was rejected.",
4456
+ error: {
4457
+ code: "QUERY_REJECTED",
4458
+ message: upstreamErrors[0]?.message || error.message,
4459
+ details: upstreamErrors
4460
+ },
4461
+ meta: { requestId: body?.request_id }
4462
+ });
4463
+ }
4464
+ }
4366
4465
  };
4466
+ var COLLECTIONS_QUERY_KEYS = [
4467
+ "filter",
4468
+ "fields",
4469
+ "include",
4470
+ "sort",
4471
+ "limit",
4472
+ "skip",
4473
+ "after",
4474
+ "count",
4475
+ "metafields",
4476
+ "availability",
4477
+ "ratings"
4478
+ ];
4479
+ function buildCollectionsQueryPayload(params) {
4480
+ const source = params || {};
4481
+ const payload = {};
4482
+ for (const key of COLLECTIONS_QUERY_KEYS) {
4483
+ if (source[key] !== void 0) payload[key] = source[key];
4484
+ }
4485
+ const filter = payload.filter && typeof payload.filter === "object" ? payload.filter : {};
4486
+ const routeHandle = source.useRouteHandle === true ? source.handle : void 0;
4487
+ if (typeof routeHandle === "string" && routeHandle.trim() !== "" && filter.handle === void 0) {
4488
+ payload.filter = { ...filter, handle: routeHandle };
4489
+ }
4490
+ return payload;
4491
+ }
4492
+ function handlesNamedBy(filter) {
4493
+ const handle = filter?.handle;
4494
+ const candidates = typeof handle === "string" ? [handle] : handle && typeof handle === "object" ? [
4495
+ handle.$eq,
4496
+ ...Array.isArray(handle.$in) ? handle.$in : []
4497
+ ] : [];
4498
+ return candidates.filter(
4499
+ (h) => typeof h === "string" && h.trim() !== ""
4500
+ );
4501
+ }
4367
4502
 
4368
4503
  // src/adapters/custom/order/urls.ts
4369
4504
  var DEFAULT_VERSION2 = "v1";
@@ -4945,6 +5080,12 @@ var CustomBackendClient = class extends BaseCommerceClient {
4945
5080
  filterRestOptions(options)
4946
5081
  );
4947
5082
  }
5083
+ async queryCollections(params, options) {
5084
+ return this.productService.queryCollections(
5085
+ params,
5086
+ filterRestOptions(options)
5087
+ );
5088
+ }
4948
5089
  // ========================================
4949
5090
  // CART OPERATIONS
4950
5091
  // ========================================