@shopkit/data-layer 1.4.6 → 1.6.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.
package/dist/index.mjs CHANGED
@@ -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
  // ========================================
@@ -3730,6 +3740,11 @@ var BaseCustomService = class {
3730
3740
  `Request failed: ${response.status} ${response.statusText}`
3731
3741
  );
3732
3742
  error.status = response.status;
3743
+ try {
3744
+ error.body = await response.json();
3745
+ } catch {
3746
+ error.body = void 0;
3747
+ }
3733
3748
  throw error;
3734
3749
  }
3735
3750
  this.logger.info("API request successful", {
@@ -3770,6 +3785,9 @@ function mapGetCollectionsByHandelsResponse(response) {
3770
3785
  function mapGetCollectionFiltersResponse(response) {
3771
3786
  return response;
3772
3787
  }
3788
+ function mapQueryCollectionsResponse(response) {
3789
+ return response?.collections || [];
3790
+ }
3773
3791
 
3774
3792
  // src/adapters/custom/product/urls.ts
3775
3793
  var DEFAULT_VERSION = "v1";
@@ -3781,7 +3799,8 @@ var PRODUCT_ENDPOINTS = {
3781
3799
  getCollectionByHandle: (v = DEFAULT_VERSION, h) => `/api/${v}/collections/handle/${encodeURIComponent(h)}`,
3782
3800
  getCollectionById: (v = DEFAULT_VERSION, id) => `/api/${v}/collections/${encodeURIComponent(id)}`,
3783
3801
  getCollectionsByHandles: (v = DEFAULT_VERSION) => `/api/${v}/collections/details`,
3784
- getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${encodeURIComponent(collectionHandle)}/filters`
3802
+ getCollectionFilters: (v = DEFAULT_VERSION, collectionHandle) => `/api/${v}/storefront/collections/${encodeURIComponent(collectionHandle)}/filters`,
3803
+ queryCollections: (v = DEFAULT_VERSION) => `/api/${v}/collections/query`
3785
3804
  };
3786
3805
 
3787
3806
  // src/adapters/custom/product/service.ts
@@ -4358,7 +4377,149 @@ var ProductService2 = class extends BaseCustomService {
4358
4377
  });
4359
4378
  }
4360
4379
  }
4380
+ /**
4381
+ * Read a page of collections, with their products and variants, from one
4382
+ * query document. A POST because the document is too nested for a URL; it is
4383
+ * still a read and answers 200.
4384
+ */
4385
+ async queryCollections(params, options) {
4386
+ try {
4387
+ const payload = buildCollectionsQueryPayload(params);
4388
+ if (selectedHandles(params)?.length === 0) {
4389
+ return formatResponse({
4390
+ success: true,
4391
+ message: "No collections selected.",
4392
+ data: [],
4393
+ meta: { pagination: { limit: 0, skip: 0, has_more: false, total: 0, next_cursor: null } }
4394
+ });
4395
+ }
4396
+ const handles = handlesNamedBy(payload.filter);
4397
+ const result = await this.request(
4398
+ PRODUCT_ENDPOINTS.queryCollections(options?.version),
4399
+ "POST",
4400
+ payload,
4401
+ {
4402
+ ...options || {},
4403
+ // Same coverage as the other collection reads: the broad tag for
4404
+ // catalog-wide purges, plus one per handle the filter names, so a
4405
+ // collection.updated / product.updated webhook reaches every page built
4406
+ // from this read. A filter that names no handle (published: true, a
4407
+ // $like, ...) cannot know its result set in advance — broad tag only.
4408
+ // No `revalidate`, as with getCollectionsByHandles.
4409
+ next: {
4410
+ ...options?.next || {},
4411
+ tags: [
4412
+ CacheTags.collections(),
4413
+ ...handles.map((h) => CacheTags.collection(h)),
4414
+ ...options?.next?.tags || []
4415
+ ]
4416
+ }
4417
+ }
4418
+ );
4419
+ const errors = Array.isArray(result?.errors) ? result.errors : [];
4420
+ if (!result?.data) {
4421
+ return formatResponse({
4422
+ success: false,
4423
+ message: "Collections query returned no data.",
4424
+ error: {
4425
+ code: "UPSTREAM_UNAVAILABLE",
4426
+ message: "No data in collections query response."
4427
+ },
4428
+ meta: { requestId: result?.request_id }
4429
+ });
4430
+ }
4431
+ return formatResponse({
4432
+ success: true,
4433
+ message: "Collections retrieved successfully.",
4434
+ data: mapQueryCollectionsResponse(result.data),
4435
+ meta: {
4436
+ pagination: result.data.paging,
4437
+ requestId: result.request_id,
4438
+ ...errors.length > 0 ? { errors } : {}
4439
+ }
4440
+ });
4441
+ } catch (error) {
4442
+ this.logger.error("Error in queryCollections", void 0, { error });
4443
+ const body = error?.body;
4444
+ if (isUpstreamUnavailable(error)) {
4445
+ return formatResponse({
4446
+ success: false,
4447
+ message: "An error occurred while processing the request.",
4448
+ error: {
4449
+ code: "UPSTREAM_UNAVAILABLE",
4450
+ message: typeof error?.status === "number" ? `Request failed: ${error.status}` : "Collections query did not complete."
4451
+ },
4452
+ meta: { requestId: body?.request_id }
4453
+ });
4454
+ }
4455
+ const upstreamErrors = Array.isArray(body?.errors) ? body.errors : [];
4456
+ return formatResponse({
4457
+ success: false,
4458
+ message: "The collections query was rejected.",
4459
+ error: {
4460
+ code: "QUERY_REJECTED",
4461
+ message: upstreamErrors[0]?.message || error.message,
4462
+ details: upstreamErrors
4463
+ },
4464
+ meta: { requestId: body?.request_id }
4465
+ });
4466
+ }
4467
+ }
4361
4468
  };
4469
+ var COLLECTIONS_QUERY_KEYS = [
4470
+ "filter",
4471
+ "fields",
4472
+ "include",
4473
+ "sort",
4474
+ "limit",
4475
+ "skip",
4476
+ "after",
4477
+ "count",
4478
+ "metafields",
4479
+ "availability",
4480
+ "ratings"
4481
+ ];
4482
+ function buildCollectionsQueryPayload(params) {
4483
+ const source = params || {};
4484
+ const payload = {};
4485
+ for (const key of COLLECTIONS_QUERY_KEYS) {
4486
+ if (source[key] !== void 0) payload[key] = source[key];
4487
+ }
4488
+ const filter = payload.filter && typeof payload.filter === "object" ? payload.filter : {};
4489
+ const handles = selectedHandles(params);
4490
+ if (handles) {
4491
+ payload.filter = { ...filter, handle: { $in: handles } };
4492
+ if (typeof payload.limit === "number" && payload.limit < handles.length) {
4493
+ payload.limit = handles.length;
4494
+ }
4495
+ return payload;
4496
+ }
4497
+ const routeHandle = source.useRouteHandle === true ? source.handle : void 0;
4498
+ if (typeof routeHandle === "string" && routeHandle.trim() !== "" && filter.handle === void 0) {
4499
+ payload.filter = { ...filter, handle: routeHandle };
4500
+ }
4501
+ return payload;
4502
+ }
4503
+ var MAX_COLLECTIONS_PER_QUERY = 10;
4504
+ function selectedHandles(params) {
4505
+ const source = params || {};
4506
+ if (!Array.isArray(source.handles)) return void 0;
4507
+ const filter = source.filter;
4508
+ if (filter && typeof filter === "object" && filter.handle !== void 0) {
4509
+ return void 0;
4510
+ }
4511
+ return source.handles.filter((h) => typeof h === "string").map((h) => h.trim()).filter((h) => h !== "").slice(0, MAX_COLLECTIONS_PER_QUERY);
4512
+ }
4513
+ function handlesNamedBy(filter) {
4514
+ const handle = filter?.handle;
4515
+ const candidates = typeof handle === "string" ? [handle] : handle && typeof handle === "object" ? [
4516
+ handle.$eq,
4517
+ ...Array.isArray(handle.$in) ? handle.$in : []
4518
+ ] : [];
4519
+ return candidates.filter(
4520
+ (h) => typeof h === "string" && h.trim() !== ""
4521
+ );
4522
+ }
4362
4523
 
4363
4524
  // src/adapters/custom/order/urls.ts
4364
4525
  var DEFAULT_VERSION2 = "v1";
@@ -4940,6 +5101,12 @@ var CustomBackendClient = class extends BaseCommerceClient {
4940
5101
  filterRestOptions(options)
4941
5102
  );
4942
5103
  }
5104
+ async queryCollections(params, options) {
5105
+ return this.productService.queryCollections(
5106
+ params,
5107
+ filterRestOptions(options)
5108
+ );
5109
+ }
4943
5110
  // ========================================
4944
5111
  // CART OPERATIONS
4945
5112
  // ========================================