@unchainedshop/cockpit-api 1.0.17 → 1.0.18

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.
Files changed (3) hide show
  1. package/README.md +6 -1
  2. package/package.json +1 -1
  3. package/src/api.ts +61 -26
package/README.md CHANGED
@@ -13,7 +13,12 @@ npm install --save @unchainedshop/cockpit-api
13
13
 
14
14
  ### Initialization
15
15
 
16
- First, import and initialize the API:
16
+ First, set your cockpit graphql endpoint to env
17
+
18
+ ```bash
19
+ COCKPIT_GRAPHQL_ENDPOINT
20
+ ```
21
+ then import and initialize the API:
17
22
 
18
23
  ```javascript
19
24
  import { CockpitAPI } from '@unchainedshop/cockpit-api';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unchainedshop/cockpit-api",
3
- "version": "1.0.17",
3
+ "version": "1.0.18",
4
4
  "description": "A package to interact with the Cockpit CMS API, including functionalities to handle GraphQL requests and various CMS content manipulations.",
5
5
  "main": "dist/index.js",
6
6
  "homepage": "https://unchained.shop",
package/src/api.ts CHANGED
@@ -1,15 +1,31 @@
1
1
  import { print } from "graphql";
2
2
  import { logger } from "./cockpit-logger.js";
3
3
  import { LRUCache } from 'lru-cache'
4
-
4
+ const { COCKPIT_GRAPHQL_ENDPOINT = '' } = process.env;
5
5
  const dataCache = new LRUCache({
6
6
  max: 100,
7
7
  ttl: 10000 * 10,
8
8
  allowStale: false,
9
9
  });
10
10
 
11
- const { COCKPIT_GRAPHQL_ENDPOINT = '' } = process.env;
12
11
 
12
+
13
+ enum ImageSizeMode {
14
+ Thumbnail = 'thumbnail',
15
+ BestFit = 'bestFit',
16
+ Resize = 'resize',
17
+ FitToWidth = 'fitToWidth',
18
+ FitToHeight = 'fitToHeight',
19
+ }
20
+ enum MimeType {
21
+ AUTO = 'auto',
22
+ GIF = 'gif',
23
+ JPEG = 'jpeg',
24
+ PNG = 'png',
25
+ WEBP = 'webp',
26
+ BMP = 'bmp'
27
+ }
28
+ ['auto', 'gif', 'jpeg', 'png', 'webp', 'bmp']
13
29
  const cockpitURL = new URL(COCKPIT_GRAPHQL_ENDPOINT);
14
30
 
15
31
  export const getTenantIds = () => {
@@ -51,19 +67,20 @@ export const generateCmsRouteReplacements = async (tenant?: string) => {
51
67
  };
52
68
 
53
69
  export const generateCollectionAndSingletonSlugRouteMap = async (tenant?: string) => {
54
- const cachedMap = dataCache.get(`SLUG_ROUTE_MAP_${tenant}`);
70
+ const cacheKey = `SLUG_ROUTE_MAP_${tenant}`;
71
+ const cachedMap = dataCache.get(cacheKey);
55
72
  if (cachedMap) return cachedMap;
73
+ const filterParams = {
74
+ fields: JSON.stringify({
75
+ data: { collection: 1, singleton: 1 },
76
+ _r: 1,
77
+ type: 1,
78
+ }),
79
+ filter: JSON.stringify({ 'data.collection': { $ne: null } }),
80
+ };
81
+
56
82
  const cmsPages = await fetch(
57
- `${cockpitURL.origin}${tenant ? `/:${tenant}/api` : "/api"}/pages/pages?locale=default&${new URLSearchParams(
58
- {
59
- fields: JSON.stringify({
60
- data: { collection: 1, singleton: 1 },
61
- _r: 1,
62
- type: 1,
63
- }),
64
- filter: JSON.stringify({ "data.collection": { $ne: null } }),
65
- },
66
- ).toString()}`,
83
+ `${cockpitURL.origin}${tenant ? `/:${tenant}/api` : "/api"}/pages/pages?locale=default&${new URLSearchParams(filterParams).toString()}`,
67
84
  );
68
85
  const pagesArr: any[] = (await cmsPages.json()) || [] as any;
69
86
  const pageMap = pagesArr.reduce((result, { data, _r }) => {
@@ -71,7 +88,7 @@ export const generateCollectionAndSingletonSlugRouteMap = async (tenant?: string
71
88
  if (!entityName) return result;
72
89
  return { ...result, [entityName]: _r };
73
90
  }, {});
74
- dataCache.set(`SLUG_ROUTE_MAP_${tenant}`, pageMap);
91
+ dataCache.set(cacheKey, pageMap);
75
92
  return pageMap;
76
93
  };
77
94
 
@@ -113,15 +130,16 @@ const buildQueryString = (params: any) => {
113
130
  };
114
131
 
115
132
  const handleErrorAndLog = (e: Error) => {
116
- console.error(e);
133
+ logger.error('Cockpit API Error', e);
117
134
  return null;
118
135
  };
119
136
 
120
137
  export const CockpitAPI = async (tenant?: string) => {
138
+ if (!COCKPIT_GRAPHQL_ENDPOINT) throw Error("COCKPIT_GRAPHQL_ENDPOINT is not set")
121
139
  const secretName = ["COCKPIT_SECRET", tenant].filter(Boolean).join("_");
122
140
  const token = process.env[secretName];
123
141
 
124
- const buildUrl = (path: string, { locale = "de", queryParams = {} }) => {
142
+ const buildUrl = (path: string, { locale = "de", queryParams = {} } = {}) => {
125
143
  const normalizedLocale = locale === "de" ? "default" : locale;
126
144
  const url = new URL(cockpitURL);
127
145
  url.pathname = `${tenant ? `/:${tenant}/api` : "/api"}${path}`;
@@ -155,7 +173,7 @@ export const CockpitAPI = async (tenant?: string) => {
155
173
  }
156
174
 
157
175
  try {
158
- logger.info(`requesting ${url}`);
176
+ logger.info(`Requesting ${url}`);
159
177
  const result = await fetch(url, {
160
178
  ...options,
161
179
  headers: {
@@ -171,16 +189,15 @@ export const CockpitAPI = async (tenant?: string) => {
171
189
  return {
172
190
  async graphQL(document: any, variables: any) {
173
191
  const query = print(document);
174
- const cockpitEndpointUrl = new URL(COCKPIT_GRAPHQL_ENDPOINT as string);
192
+ const cockpitEndpointUrl = new URL(COCKPIT_GRAPHQL_ENDPOINT);
175
193
  if (tenant) {
176
194
  cockpitEndpointUrl.pathname = `/:${tenant}${cockpitEndpointUrl.pathname}`;
177
195
  }
178
- const fetchResult = await fetchData(cockpitEndpointUrl, {
196
+ return fetchData(cockpitEndpointUrl, {
179
197
  method: "POST",
180
198
  headers: { "Content-Type": "application/json" },
181
199
  body: JSON.stringify({ query, variables }),
182
200
  });
183
- return fetchResult;
184
201
  },
185
202
 
186
203
  async getContentItem(
@@ -235,24 +252,20 @@ export const CockpitAPI = async (tenant?: string) => {
235
252
  async postContentItem(model: string, item: any) {
236
253
  if (!model) throw new Error("Cockpit: Please provide a model");
237
254
  const url = buildUrl(`/content/item/${model}`, {});
238
- const result = await fetchData(url, {
255
+ return fetchData(url, {
239
256
  method: "POST",
240
257
  headers: { "Content-Type": "application/json" },
241
258
  body: JSON.stringify({ data: item }),
242
259
  });
243
-
244
- return result;
245
260
  },
246
261
  async deleteContentItem(model: string, id?: string) {
247
262
  if (!model || !id)
248
263
  throw new Error("Cockpit: Please provide a model and id");
249
264
  const url = buildUrl(`/content/item/${model}/${id}`, {});
250
- const result = await fetchData(url, {
265
+ return fetchData(url, {
251
266
  method: "DELETE",
252
267
  headers: { "Content-Type": "application/json" },
253
268
  });
254
-
255
- return result;
256
269
  },
257
270
 
258
271
  async pages(locale = "default", queryParams = {}) {
@@ -304,6 +317,28 @@ export const CockpitAPI = async (tenant?: string) => {
304
317
  const url = buildUrl("/pages/settings", { locale });
305
318
  return fetchData(url);
306
319
  },
320
+ async healthCheck() {
321
+ const url = buildUrl("/system/healthcheck");
322
+ return fetchData(url);
323
+ },
324
+ async lokalize(projectName: string, locale = "default", nested = null) {
325
+ if (!projectName)
326
+ throw new Error("GetCockpit: Please provide projectName");
327
+ const url = buildUrl(`/lokalize/project/${projectName}`, { locale, queryParams: { nested } });
328
+ return fetchData(url);
329
+ },
330
+ async assetById(assetId: string) {
331
+ if (!assetId)
332
+ throw new Error("GetCockpit: Please provide assetId");
333
+ const url = buildUrl(`/assets/${assetId}`);
334
+ return fetchData(url);
335
+ },
336
+ async imageAssetById(assetId: string, queryParams?: { m?: ImageSizeMode; w?: number; h?: number; q?: number; mime?: MimeType; re?: number; t?: string; o?: number; }) {
337
+ if (!assetId)
338
+ throw new Error("GetCockpit: Please provide assetId");
339
+ const url = buildUrl(`/assets/image/${assetId}`, { queryParams });
340
+ return fetchData(url);
341
+ },
307
342
  async getFullRouteForSlug(slug: string) {
308
343
  const routeSlugMap =
309
344
  await generateCollectionAndSingletonSlugRouteMap(tenant);