@agility/content-fetch 2.0.15-beta.0 → 2.0.15

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/README.md CHANGED
@@ -59,19 +59,31 @@ const contentItems = await api.getContentItem({
59
59
  })
60
60
  ```
61
61
 
62
- ### Naming the app that makes the requests
62
+ ### Telling "not found" apart from "failed" (`throwOnError`)
63
63
 
64
- Set `source` to say which app is calling, so usage can be reported by where it comes from (your production site, a staging site, a mobile app, a build job):
64
+ By default a request that fails (a 5xx, a timeout, a network error, a body that isn't JSON) returns `undefined`, the same as a 404. With a data cache (Next.js ISR or `"use cache"`), that `undefined` can be cached, and one failed request becomes a lasting "not found".
65
+
66
+ Set `throwOnError: true` to tell them apart. A 404 still returns `undefined`; anything else throws a `FetchApiError` with `status` (undefined when no response came back) and `url`, so nothing is cached and the next request tries again. It is off by default, so existing code is unchanged.
65
67
 
66
68
  ```javascript
67
- const api = agility.getApi({
68
- guid: "[guid]",
69
- apiKey: "[your-api-key]",
70
- source: "prod-website",
71
- })
69
+ import agility, { FetchApiError } from "@agility/content-fetch"
70
+
71
+ const api = agility.getApi({ guid: "[guid]", apiKey: "[your-api-key]", throwOnError: true })
72
+
73
+ const page = await api.getPage({ pageID: 2, locale: "en-us" }) // undefined only for a 404
72
74
  ```
73
75
 
74
- It is sent on every request as the `Agility-Source` header. It must be at most 64 characters of letters, digits, spaces and `_ . : / -`; anything else throws a `TypeError` from `getApi`. When `source` is not set, no header is sent. It is a label, not a credential: it doesn't change what the API returns or how responses are cached.
76
+ ### Returning only some fields (`fields`)
77
+
78
+ `getContentList` takes `fields`, a comma separated list of the fields to return on each item. Names are case-sensitive and match the API's casing. Filters, sort, paging and `totalCount` are unaffected.
79
+
80
+ ```javascript
81
+ const posts = await api.getContentList({
82
+ referenceName: "posts",
83
+ locale: "en-us",
84
+ fields: "fields.title,fields.uRL",
85
+ })
86
+ ```
75
87
 
76
88
  ## Documentation
77
89
 
package/dist/browser.js CHANGED
@@ -68,7 +68,7 @@
68
68
  let urlPath = `${config.baseUrl}/${apiFetchOrPreview}/${locale}`;
69
69
  return urlPath;
70
70
  }
71
- function buildPathUrl(contentType, referenceName, skip, take, sort, direction, filters, filtersLogicOperator, filterString, contentLinkDepth, expandAllContentLinks) {
71
+ function buildPathUrl(contentType, referenceName, skip, take, sort, direction, filters, filtersLogicOperator, filterString, contentLinkDepth, expandAllContentLinks, fields) {
72
72
  let url = `/${contentType}/${referenceName}?contentLinkDepth=${contentLinkDepth}&`;
73
73
  filtersLogicOperator = filtersLogicOperator ? ` ${filtersLogicOperator} ` : " AND ";
74
74
  if (sort) {
@@ -96,13 +96,11 @@
96
96
  if (expandAllContentLinks) {
97
97
  url += `expandAllContentLinks=${expandAllContentLinks}&`;
98
98
  }
99
+ if (fields) {
100
+ url += `fields=${encodeURIComponent(fields)}&`;
101
+ }
99
102
  return url;
100
103
  }
101
- var SOURCE_HEADER = "Agility-Source";
102
- var SOURCE_PATTERN = /^[A-Za-z0-9 _.:/-]{0,64}$/;
103
- function isValidSource(source) {
104
- return typeof source === "string" && SOURCE_PATTERN.test(source);
105
- }
106
104
  function buildAuthHeader(config) {
107
105
  let defaultAuthHeaders = {
108
106
  APIKey: config.apiKey,
@@ -115,13 +113,6 @@
115
113
  ...defaultAuthHeaders,
116
114
  ...config.headers
117
115
  };
118
- if (typeof config.source === "string" && config.source.length > 0) {
119
- for (const key of Object.keys(headers)) {
120
- if (key.toLowerCase() === SOURCE_HEADER.toLowerCase())
121
- delete headers[key];
122
- }
123
- headers[SOURCE_HEADER] = config.source;
124
- }
125
116
  return headers;
126
117
  }
127
118
  function isHttps(url) {
@@ -142,6 +133,16 @@
142
133
  Error.captureStackTrace?.(this, asserter || this.constructor);
143
134
  }
144
135
  };
136
+ var FetchApiError = class extends Error {
137
+ constructor(message, url, status, cause) {
138
+ super(message);
139
+ this.name = "FetchApiError";
140
+ this.url = url;
141
+ this.status = status;
142
+ if (cause !== void 0)
143
+ this.cause = cause;
144
+ }
145
+ };
145
146
 
146
147
  // src/methods/getSitemapFlat.ts
147
148
  function getSitemapFlat(requestParams) {
@@ -225,7 +226,7 @@
225
226
  requestParams.referenceName = sanitizeReferenceName(requestParams.referenceName);
226
227
  requestParams = { ...defaultParams2, ...requestParams };
227
228
  const req = {
228
- url: buildPathUrl("list", requestParams.referenceName, requestParams.skip, requestParams.take, requestParams.sort, requestParams.direction, requestParams.filters, requestParams.filtersLogicOperator, requestParams.filterString, requestParams.contentLinkDepth, requestParams.expandAllContentLinks),
229
+ url: buildPathUrl("list", requestParams.referenceName, requestParams.skip, requestParams.take, requestParams.sort, requestParams.direction, requestParams.filters, requestParams.filtersLogicOperator, requestParams.filterString, requestParams.contentLinkDepth, requestParams.expandAllContentLinks, requestParams.fields),
229
230
  method: "get",
230
231
  baseURL: buildRequestUrlPath(this.config, requestParams.locale ? requestParams.locale : requestParams.languageCode),
231
232
  headers: buildAuthHeader(this.config),
@@ -283,6 +284,9 @@
283
284
  } else if (requestParams.expandAllContentLinks && typeof requestParams.expandAllContentLinks !== "boolean") {
284
285
  throw new TypeError2("ExpandAllContentLinks parameter must be a value of true or false", validateRequestParams4);
285
286
  }
287
+ if (requestParams.fields !== void 0 && requestParams.fields !== null && typeof requestParams.fields !== "string") {
288
+ throw new TypeError2('Fields parameter must be a comma separated string, for example "fields.title,fields.uRL"', validateRequestParams4);
289
+ }
286
290
  return true;
287
291
  }
288
292
  var defaultParams2 = {
@@ -570,8 +574,6 @@
570
574
  throw new TypeError2("When specifying a cache maxAge, you must set a number value in miliseconds, i.e. 180000 (3 mins).");
571
575
  } else if (configParams.baseUrl && !isHttps(configParams.baseUrl)) {
572
576
  throw new TypeError2(`When specifying a baseUrl (${configParams.baseUrl}), it must be over HTTPs.`);
573
- } else if (configParams.source !== void 0 && configParams.source !== null && !isValidSource(configParams.source)) {
574
- throw new TypeError2('When specifying a source, it must be at most 64 characters of letters, digits, spaces and _ . : / -, i.e. "prod-website".');
575
577
  } else {
576
578
  return;
577
579
  }
@@ -686,6 +688,9 @@
686
688
  return;
687
689
  }
688
690
  logError({ config: this.config, message: `AgilityCMS Fetch API ERROR: Request returned a ${response.status} (${response.statusText}) response for ${fullUrl}. Duration: ${duration}ms.${bodySnippet}` });
691
+ if (this.config.throwOnError) {
692
+ throw new FetchApiError(`AgilityCMS Fetch API: ${response.status} ${response.statusText} for ${fullUrl}`, fullUrl, response.status);
693
+ }
689
694
  return;
690
695
  }
691
696
  let data = await response.json();
@@ -711,6 +716,8 @@
711
716
  }
712
717
  return data;
713
718
  } catch (error) {
719
+ if (error instanceof FetchApiError)
720
+ throw error;
714
721
  const duration = Date.now() - startTime;
715
722
  logDebugDetails({
716
723
  config: this.config,
@@ -728,6 +735,9 @@
728
735
  }
729
736
  });
730
737
  logError({ config: this.config, message: `AgilityCMS Fetch API ERROR: Request failed for ${fullUrl} after ${duration}ms ... ${error}` });
738
+ if (this.config.throwOnError) {
739
+ throw new FetchApiError(`AgilityCMS Fetch API: request failed for ${fullUrl}: ${error}`, fullUrl, void 0, error);
740
+ }
731
741
  }
732
742
  }
733
743
  };
@@ -740,6 +750,7 @@
740
750
 
741
751
  // src/index.ts
742
752
  module.exports = {
743
- getApi
753
+ getApi,
754
+ FetchApiError
744
755
  };
745
756
  })();
package/dist/index.d.ts CHANGED
@@ -10,4 +10,5 @@ import { SEOProperties, SEORobots } from "./types/SEO";
10
10
  import { ApiClientInstance, getApi } from "./api-client";
11
11
  import { ContentReference } from "./types/ContentReference";
12
12
  export type { ApiClientInstance, Config, ContentItem, ContentList, ContentReference, Filter, Gallery, Page, PageScripts, GeoProperties, GeoAi, SchemaType, LlmsInclude, AiCrawl, StructuredData, SEOProperties, SEORobots };
13
- export { getApi };
13
+ import { FetchApiError } from "./types/errors/Errors";
14
+ export { getApi, FetchApiError };
@@ -109,6 +109,12 @@ export interface ContentListRequestParams {
109
109
  */
110
110
  filters?: Array<Filter>;
111
111
  filtersLogicOperator?: FilterLogicOperator;
112
+ /**
113
+ * A comma separated list of the fields to return, for example "fields.title,fields.uRL".
114
+ * Only those fields come back on each item. Names are case-sensitive and must match the
115
+ * API's casing. Filters, sort, paging and totalCount are unaffected.
116
+ */
117
+ fields?: string;
112
118
  }
113
119
  declare function getContentList(this: ApiClientInstance, requestParams: ContentListRequestParams): Promise<ContentList>;
114
120
  export default getContentList;
package/dist/node.js CHANGED
@@ -19,6 +19,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  // src/index.ts
20
20
  var src_exports = {};
21
21
  __export(src_exports, {
22
+ FetchApiError: () => FetchApiError,
22
23
  getApi: () => getApi
23
24
  });
24
25
  module.exports = __toCommonJS(src_exports);
@@ -86,7 +87,7 @@ function buildRequestUrlPath(config, locale) {
86
87
  let urlPath = `${config.baseUrl}/${apiFetchOrPreview}/${locale}`;
87
88
  return urlPath;
88
89
  }
89
- function buildPathUrl(contentType, referenceName, skip, take, sort, direction, filters, filtersLogicOperator, filterString, contentLinkDepth, expandAllContentLinks) {
90
+ function buildPathUrl(contentType, referenceName, skip, take, sort, direction, filters, filtersLogicOperator, filterString, contentLinkDepth, expandAllContentLinks, fields) {
90
91
  let url = `/${contentType}/${referenceName}?contentLinkDepth=${contentLinkDepth}&`;
91
92
  filtersLogicOperator = filtersLogicOperator ? ` ${filtersLogicOperator} ` : " AND ";
92
93
  if (sort) {
@@ -114,13 +115,11 @@ function buildPathUrl(contentType, referenceName, skip, take, sort, direction, f
114
115
  if (expandAllContentLinks) {
115
116
  url += `expandAllContentLinks=${expandAllContentLinks}&`;
116
117
  }
118
+ if (fields) {
119
+ url += `fields=${encodeURIComponent(fields)}&`;
120
+ }
117
121
  return url;
118
122
  }
119
- var SOURCE_HEADER = "Agility-Source";
120
- var SOURCE_PATTERN = /^[A-Za-z0-9 _.:/-]{0,64}$/;
121
- function isValidSource(source) {
122
- return typeof source === "string" && SOURCE_PATTERN.test(source);
123
- }
124
123
  function buildAuthHeader(config) {
125
124
  let defaultAuthHeaders = {
126
125
  APIKey: config.apiKey,
@@ -133,13 +132,6 @@ function buildAuthHeader(config) {
133
132
  ...defaultAuthHeaders,
134
133
  ...config.headers
135
134
  };
136
- if (typeof config.source === "string" && config.source.length > 0) {
137
- for (const key of Object.keys(headers)) {
138
- if (key.toLowerCase() === SOURCE_HEADER.toLowerCase())
139
- delete headers[key];
140
- }
141
- headers[SOURCE_HEADER] = config.source;
142
- }
143
135
  return headers;
144
136
  }
145
137
  function isHttps(url) {
@@ -160,6 +152,16 @@ var TypeError2 = class extends Error {
160
152
  Error.captureStackTrace?.(this, asserter || this.constructor);
161
153
  }
162
154
  };
155
+ var FetchApiError = class extends Error {
156
+ constructor(message, url, status, cause) {
157
+ super(message);
158
+ this.name = "FetchApiError";
159
+ this.url = url;
160
+ this.status = status;
161
+ if (cause !== void 0)
162
+ this.cause = cause;
163
+ }
164
+ };
163
165
 
164
166
  // src/methods/getSitemapFlat.ts
165
167
  function getSitemapFlat(requestParams) {
@@ -243,7 +245,7 @@ function getContentList(requestParams) {
243
245
  requestParams.referenceName = sanitizeReferenceName(requestParams.referenceName);
244
246
  requestParams = { ...defaultParams2, ...requestParams };
245
247
  const req = {
246
- url: buildPathUrl("list", requestParams.referenceName, requestParams.skip, requestParams.take, requestParams.sort, requestParams.direction, requestParams.filters, requestParams.filtersLogicOperator, requestParams.filterString, requestParams.contentLinkDepth, requestParams.expandAllContentLinks),
248
+ url: buildPathUrl("list", requestParams.referenceName, requestParams.skip, requestParams.take, requestParams.sort, requestParams.direction, requestParams.filters, requestParams.filtersLogicOperator, requestParams.filterString, requestParams.contentLinkDepth, requestParams.expandAllContentLinks, requestParams.fields),
247
249
  method: "get",
248
250
  baseURL: buildRequestUrlPath(this.config, requestParams.locale ? requestParams.locale : requestParams.languageCode),
249
251
  headers: buildAuthHeader(this.config),
@@ -301,6 +303,9 @@ function validateRequestParams4(requestParams) {
301
303
  } else if (requestParams.expandAllContentLinks && typeof requestParams.expandAllContentLinks !== "boolean") {
302
304
  throw new TypeError2("ExpandAllContentLinks parameter must be a value of true or false", validateRequestParams4);
303
305
  }
306
+ if (requestParams.fields !== void 0 && requestParams.fields !== null && typeof requestParams.fields !== "string") {
307
+ throw new TypeError2('Fields parameter must be a comma separated string, for example "fields.title,fields.uRL"', validateRequestParams4);
308
+ }
304
309
  return true;
305
310
  }
306
311
  var defaultParams2 = {
@@ -588,8 +593,6 @@ function validateConfigParams(configParams) {
588
593
  throw new TypeError2("When specifying a cache maxAge, you must set a number value in miliseconds, i.e. 180000 (3 mins).");
589
594
  } else if (configParams.baseUrl && !isHttps(configParams.baseUrl)) {
590
595
  throw new TypeError2(`When specifying a baseUrl (${configParams.baseUrl}), it must be over HTTPs.`);
591
- } else if (configParams.source !== void 0 && configParams.source !== null && !isValidSource(configParams.source)) {
592
- throw new TypeError2('When specifying a source, it must be at most 64 characters of letters, digits, spaces and _ . : / -, i.e. "prod-website".');
593
596
  } else {
594
597
  return;
595
598
  }
@@ -704,6 +707,9 @@ var ApiClient = class {
704
707
  return;
705
708
  }
706
709
  logError({ config: this.config, message: `AgilityCMS Fetch API ERROR: Request returned a ${response.status} (${response.statusText}) response for ${fullUrl}. Duration: ${duration}ms.${bodySnippet}` });
710
+ if (this.config.throwOnError) {
711
+ throw new FetchApiError(`AgilityCMS Fetch API: ${response.status} ${response.statusText} for ${fullUrl}`, fullUrl, response.status);
712
+ }
707
713
  return;
708
714
  }
709
715
  let data = await response.json();
@@ -729,6 +735,8 @@ var ApiClient = class {
729
735
  }
730
736
  return data;
731
737
  } catch (error) {
738
+ if (error instanceof FetchApiError)
739
+ throw error;
732
740
  const duration = Date.now() - startTime;
733
741
  logDebugDetails({
734
742
  config: this.config,
@@ -746,6 +754,9 @@ var ApiClient = class {
746
754
  }
747
755
  });
748
756
  logError({ config: this.config, message: `AgilityCMS Fetch API ERROR: Request failed for ${fullUrl} after ${duration}ms ... ${error}` });
757
+ if (this.config.throwOnError) {
758
+ throw new FetchApiError(`AgilityCMS Fetch API: request failed for ${fullUrl}: ${error}`, fullUrl, void 0, error);
759
+ }
749
760
  }
750
761
  }
751
762
  };
@@ -758,9 +769,11 @@ function getApi(config) {
758
769
 
759
770
  // src/index.ts
760
771
  module.exports = {
761
- getApi
772
+ getApi,
773
+ FetchApiError
762
774
  };
763
775
  // Annotate the CommonJS export names for ESM import in node:
764
776
  0 && (module.exports = {
777
+ FetchApiError,
765
778
  getApi
766
779
  });
@@ -18,13 +18,6 @@ export interface Config {
18
18
  */
19
19
  apiKey?: string | null;
20
20
  locale?: string | null;
21
- /**
22
- * Names the app making the requests, such as "prod-website", "staging-website" or "ios-app".
23
- * Sent on every request as the `Agility-Source` header, so API usage can be reported by where it
24
- * comes from. At most 64 characters of letters, digits, space and `_ . : / -`. Optional: when it
25
- * is not set (or is ""), no header is sent. It is a label, not a credential.
26
- */
27
- source?: string | null;
28
21
  /**
29
22
  * Additional headers to include in the request.
30
23
  */
@@ -55,5 +48,19 @@ export interface Config {
55
48
  caching?: {
56
49
  maxAge?: number;
57
50
  };
51
+ /**
52
+ * Throw when a request fails, instead of returning `undefined`. Default is false.
53
+ *
54
+ * By default every failure (a 5xx, a timeout, a network error, a body that isn't JSON)
55
+ * returns `undefined`, the same as a 404. With a data cache (Next.js ISR or "use cache"),
56
+ * that `undefined` can be cached, so one failed request becomes a lasting "not found".
57
+ *
58
+ * When true:
59
+ * - a 404 still returns `undefined` (the item, page or sitemap doesn't exist);
60
+ * - anything else throws a `FetchApiError` with the `status` (undefined when no response
61
+ * came back or the body wasn't JSON) and the request `url`, so the render fails,
62
+ * nothing is cached, and the next request tries again.
63
+ */
64
+ throwOnError?: boolean;
58
65
  fetchConfig?: any;
59
66
  }
@@ -17,6 +17,17 @@ export declare class TypeError extends Error {
17
17
  */
18
18
  constructor(message: string, asserter?: any);
19
19
  }
20
+ /**
21
+ * Thrown by a client created with `throwOnError: true` when a request fails for any
22
+ * reason other than a 404.
23
+ */
24
+ export declare class FetchApiError extends Error {
25
+ /** The HTTP status, or undefined when no response came back (network error, timeout) or the body wasn't JSON. */
26
+ status?: number;
27
+ /** The request URL. */
28
+ url: string;
29
+ constructor(message: string, url: string, status?: number, cause?: unknown);
30
+ }
20
31
  export declare class URIError extends Error {
21
32
  constructor(message?: string, asserter?: any);
22
33
  }
package/dist/utils.d.ts CHANGED
@@ -40,11 +40,8 @@ declare function logDebugDetails({ config, details }: {
40
40
  details: DebugDetails;
41
41
  }): void;
42
42
  declare function buildRequestUrlPath(config: any, locale: any): string;
43
- declare function buildPathUrl(contentType: any, referenceName: any, skip: any, take: any, sort: any, direction: any, filters: any, filtersLogicOperator: any, filterString: any, contentLinkDepth: any, expandAllContentLinks: any): string;
44
- /** The request header that carries the `source` setting. */
45
- declare const SOURCE_HEADER = "Agility-Source";
46
- declare function isValidSource(source: unknown): boolean;
43
+ declare function buildPathUrl(contentType: any, referenceName: any, skip: any, take: any, sort: any, direction: any, filters: any, filtersLogicOperator: any, filterString: any, contentLinkDepth: any, expandAllContentLinks: any, fields?: any): string;
47
44
  declare function buildAuthHeader(config: any): any;
48
45
  declare function isHttps(url: any): boolean;
49
- export { buildPathUrl, buildAuthHeader, buildRequestUrlPath, isValidSource, SOURCE_HEADER, isHttps, logError, logDebug, logInfo, logWarning, logDebugDetails, headersToObject };
46
+ export { buildPathUrl, buildAuthHeader, buildRequestUrlPath, isHttps, logError, logDebug, logInfo, logWarning, logDebugDetails, headersToObject };
50
47
  export type { DebugDetails };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agility/content-fetch",
3
- "version": "2.0.15-beta.0",
3
+ "version": "2.0.15",
4
4
  "description": "JS/TS library for the Agility Fetch API",
5
5
  "repository": {
6
6
  "type": "git",