@shushed/helpers 0.0.251 → 0.0.252

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.
@@ -141,6 +141,18 @@ class CentraHelper extends env_1.default {
141
141
  getCacheKeyForCentraPricelist(pricelistExternalId) {
142
142
  return `${this.getCacheKeyForCentraPricelists()}_${pricelistExternalId}`;
143
143
  }
144
+ getCacheKeyForCentraCategory(categoryId) {
145
+ return `centra_${this.shaToken}_category_${categoryId}`;
146
+ }
147
+ getCacheKeyForCentraCategories() {
148
+ return `centra_${this.shaToken}_categories`;
149
+ }
150
+ getCacheKeyForCentraMeasurementCharts() {
151
+ return `centra_${this.shaToken}_measurement_charts`;
152
+ }
153
+ getCacheKeyForCentraMeasurementChart(name) {
154
+ return `centra_${this.shaToken}_measurement_chart_${name}`;
155
+ }
144
156
  async fetchCountries(iso2Codes) {
145
157
  const result = [];
146
158
  const limit = 200;
@@ -1093,5 +1105,269 @@ class CentraHelper extends env_1.default {
1093
1105
  }
1094
1106
  return centraSizeName;
1095
1107
  }
1108
+ async fetchCentraCategories(categoryIds) {
1109
+ const result = [];
1110
+ const limit = 200;
1111
+ let page = 0;
1112
+ let hasNextPage = true;
1113
+ do {
1114
+ const data = await this.fetch(this.graphqlUrl, {
1115
+ method: 'POST',
1116
+ body: JSON.stringify({
1117
+ query: `
1118
+ query GetCategories($limit: Int, $page: Int${categoryIds ? `, $categoryIds: CategoryFilter` : ''}) {
1119
+ categories(${categoryIds ? `where: $categoryIds, ` : ''}limit: $limit, page: $page) {
1120
+ id
1121
+ name
1122
+ uri
1123
+ isTopCategory
1124
+ }
1125
+ }
1126
+ `,
1127
+ variables: {
1128
+ page,
1129
+ limit,
1130
+ categoryIds: categoryIds ? { uri: categoryIds } : undefined
1131
+ }
1132
+ })
1133
+ });
1134
+ if (CentraHelper.isCentraErrors(data)) {
1135
+ return data;
1136
+ }
1137
+ if ((data.data?.categories?.length || 0) < limit) {
1138
+ hasNextPage = false;
1139
+ }
1140
+ else {
1141
+ page++;
1142
+ }
1143
+ for (const category of data.data?.categories || []) {
1144
+ result.push({
1145
+ id: category.id,
1146
+ name: category.name,
1147
+ uri: category.uri,
1148
+ isTopCategory: category.isTopCategory
1149
+ });
1150
+ }
1151
+ } while (hasNextPage);
1152
+ return result;
1153
+ }
1154
+ async getCentraCategories(categoryIds, alwaysFetch = false) {
1155
+ if (categoryIds && !categoryIds.length) {
1156
+ return {};
1157
+ }
1158
+ let categoryInCache = {};
1159
+ let dedupedCategoryIds = [];
1160
+ let categoriesToFetch = null;
1161
+ if (!alwaysFetch) {
1162
+ if (!categoryIds) {
1163
+ categoryIds = await this.get(this.getCacheKeyForCentraCategories(), 'env', {
1164
+ isEphemeral: true,
1165
+ encrypted: false,
1166
+ }).then(x => x ? JSON.parse(x) : null);
1167
+ }
1168
+ if (categoryIds) {
1169
+ dedupedCategoryIds = categoryIds.filter((x, index, self) => self.indexOf(x) === index);
1170
+ const cachedValues = await this.get(dedupedCategoryIds.map(x => this.getCacheKeyForCentraCategory(x)), 'env', {
1171
+ isEphemeral: true,
1172
+ encrypted: false,
1173
+ });
1174
+ categoryInCache = Object.fromEntries(Object.entries(cachedValues)
1175
+ .map(([key, value]) => [key, value ? JSON.parse(value || 'null') : undefined])
1176
+ .filter((entry) => entry[1]));
1177
+ categoriesToFetch = dedupedCategoryIds.filter(x => !categoryInCache[x]);
1178
+ }
1179
+ }
1180
+ const categoryToSet = {};
1181
+ if (!categoriesToFetch || categoriesToFetch.length) {
1182
+ const categoriesFetched = await this.fetchCentraCategories(categoriesToFetch);
1183
+ if (CentraHelper.isCentraErrors(categoriesFetched)) {
1184
+ if (categoriesToFetch) {
1185
+ for (const categoryId of categoriesToFetch) {
1186
+ categoryToSet[categoryId] = new Error(`Failed to fetch category ${categoryId}: ${categoriesFetched.errors.map((x) => x.message).join(', ')}`);
1187
+ }
1188
+ }
1189
+ else {
1190
+ return new Error(`Failed to fetch categories: ${categoriesFetched.errors.map((x) => x.message).join(', ')}`);
1191
+ }
1192
+ }
1193
+ else {
1194
+ for (const category of categoriesFetched) {
1195
+ categoryToSet[category.uri] = category;
1196
+ }
1197
+ await this.set(Object.entries(categoryToSet)
1198
+ .filter((entry) => !(entry[1] instanceof Error))
1199
+ .map(([key, value]) => ({ name: this.getCacheKeyForCentraCategory(key), value: JSON.stringify(value) })), 'env', { ephemeralMs: CACHE_EXPIRATION_MS, encrypted: false });
1200
+ if (!categoriesToFetch) {
1201
+ await this.set([{
1202
+ name: this.getCacheKeyForCentraCategories(),
1203
+ value: JSON.stringify(Object.keys(categoryToSet)),
1204
+ }], 'env', { ephemeralMs: CACHE_EXPIRATION_MS, encrypted: false });
1205
+ }
1206
+ }
1207
+ }
1208
+ return Object.assign({}, categoryInCache, categoryToSet);
1209
+ }
1210
+ async fetchCentraMeasurementCharts() {
1211
+ const result = [];
1212
+ const limit = 200;
1213
+ let page = 0;
1214
+ let hasNextPage = true;
1215
+ do {
1216
+ const data = await this.fetch(this.graphqlUrl, {
1217
+ method: 'POST',
1218
+ body: JSON.stringify({
1219
+ query: `
1220
+ query GetMeasurementCharts($limit: Int, $page: Int) {
1221
+ measurementCharts(limit: $limit, page: $page) {
1222
+ id
1223
+ name
1224
+ }
1225
+ }
1226
+ `,
1227
+ variables: { page, limit }
1228
+ })
1229
+ });
1230
+ if (CentraHelper.isCentraErrors(data)) {
1231
+ return data;
1232
+ }
1233
+ if ((data.data?.measurementCharts?.length || 0) < limit) {
1234
+ hasNextPage = false;
1235
+ }
1236
+ else {
1237
+ page++;
1238
+ }
1239
+ for (const chart of data.data?.measurementCharts || []) {
1240
+ result.push({
1241
+ id: chart.id,
1242
+ name: chart.name
1243
+ });
1244
+ }
1245
+ } while (hasNextPage);
1246
+ return result;
1247
+ }
1248
+ async getCentraMeasurementCharts(alwaysFetch = false) {
1249
+ let chartInCache = {};
1250
+ let dedupedChartNamesInCache = [];
1251
+ let chartsToFetch = null;
1252
+ if (!alwaysFetch) {
1253
+ const chartNamesInCache = await this.get(this.getCacheKeyForCentraMeasurementCharts(), 'env', {
1254
+ isEphemeral: true,
1255
+ encrypted: false,
1256
+ }).then(x => x ? JSON.parse(x) : null);
1257
+ if (chartNamesInCache) {
1258
+ dedupedChartNamesInCache = chartNamesInCache.filter((x, index, self) => self.indexOf(x) === index);
1259
+ const cachedValues = await this.get(dedupedChartNamesInCache.map(x => this.getCacheKeyForCentraMeasurementChart(x)), 'env', {
1260
+ isEphemeral: true,
1261
+ encrypted: false,
1262
+ });
1263
+ chartInCache = Object.fromEntries(Object.entries(cachedValues)
1264
+ .map(([key, value]) => [key, value ? JSON.parse(value || 'null') : undefined])
1265
+ .filter((entry) => entry[1]));
1266
+ chartsToFetch = dedupedChartNamesInCache.filter(x => !chartInCache[x]);
1267
+ }
1268
+ }
1269
+ const chartToSet = {};
1270
+ if (!chartsToFetch || chartsToFetch.length) {
1271
+ const charts = await this.fetchCentraMeasurementCharts();
1272
+ if (CentraHelper.isCentraErrors(charts)) {
1273
+ return new Error(`Failed to fetch measurement charts: ${charts.errors.map((x) => x.message).join(', ')}`);
1274
+ }
1275
+ else {
1276
+ for (const chart of charts) {
1277
+ chartToSet[chart.name] = chart;
1278
+ }
1279
+ await this.set(Object.entries(chartToSet)
1280
+ .filter((entry) => !(entry[1] instanceof Error))
1281
+ .map(([key, value]) => ({ name: this.getCacheKeyForCentraMeasurementChart(key), value: JSON.stringify(value) })), 'env', { ephemeralMs: CACHE_EXPIRATION_MS, encrypted: false });
1282
+ await this.set([{
1283
+ name: this.getCacheKeyForCentraMeasurementCharts(),
1284
+ value: JSON.stringify(Object.keys(chartToSet)),
1285
+ }], 'env', { ephemeralMs: CACHE_EXPIRATION_MS, encrypted: false });
1286
+ }
1287
+ }
1288
+ return Object.assign({}, chartInCache, chartToSet);
1289
+ }
1290
+ async getCentraDisplaysByUris(uris) {
1291
+ if (uris.length === 0) {
1292
+ return {};
1293
+ }
1294
+ const uniqueUris = [...new Set(uris.filter(Boolean))];
1295
+ const result = {};
1296
+ for (const uri of uniqueUris) {
1297
+ result[uri] = [];
1298
+ }
1299
+ const limit = uniqueUris.length > 200 ? 200 : uniqueUris.length;
1300
+ let nextCursor = null;
1301
+ do {
1302
+ try {
1303
+ const data = await this.fetch(this.graphqlUrl, {
1304
+ method: 'POST',
1305
+ body: JSON.stringify({
1306
+ query: `
1307
+ query displayConnection($input: DisplayFilter, $limit: Int, $after: String) {
1308
+ displayConnection(where: $input, first: $limit, after: $after) {
1309
+ pageInfo {
1310
+ endCursor
1311
+ hasNextPage
1312
+ }
1313
+ edges {
1314
+ node {
1315
+ id
1316
+ uri
1317
+ name
1318
+ product {
1319
+ id
1320
+ externalId
1321
+ }
1322
+ productVariants {
1323
+ id
1324
+ externalId
1325
+ }
1326
+ }
1327
+ }
1328
+ }
1329
+ }
1330
+ `,
1331
+ variables: {
1332
+ input: {
1333
+ uri: {
1334
+ contains: uniqueUris
1335
+ }
1336
+ },
1337
+ after: nextCursor,
1338
+ limit: limit
1339
+ }
1340
+ })
1341
+ });
1342
+ if (CentraHelper.isCentraErrors(data)) {
1343
+ return new Error(`Failed to query displays by URIs: ${data.errors.map(e => e.message).join(', ')}`);
1344
+ }
1345
+ const displayConnection = data.data?.displayConnection;
1346
+ if (displayConnection?.pageInfo?.hasNextPage &&
1347
+ displayConnection.pageInfo.endCursor &&
1348
+ displayConnection.pageInfo.endCursor !== nextCursor) {
1349
+ nextCursor = displayConnection.pageInfo.endCursor;
1350
+ }
1351
+ else {
1352
+ nextCursor = null;
1353
+ }
1354
+ if (displayConnection?.edges?.length) {
1355
+ for (const edge of displayConnection.edges) {
1356
+ const display = edge.node;
1357
+ if (display.uri && uniqueUris.includes(display.uri)) {
1358
+ if (!result[display.uri]) {
1359
+ result[display.uri] = [];
1360
+ }
1361
+ result[display.uri].push(display);
1362
+ }
1363
+ }
1364
+ }
1365
+ }
1366
+ catch (error) {
1367
+ return error instanceof Error ? error : new Error(String(error));
1368
+ }
1369
+ } while (nextCursor !== null);
1370
+ return result;
1371
+ }
1096
1372
  }
1097
1373
  exports.default = CentraHelper;
@@ -1,5 +1,28 @@
1
1
  import EnvEngine from './env';
2
2
  import Runtime from './runtime';
3
+ export type BasicCentraCategory = {
4
+ id: number;
5
+ name: string;
6
+ uri: string;
7
+ isTopCategory: boolean;
8
+ };
9
+ export type BasicCentraMeasurementChart = {
10
+ id: number;
11
+ name: string;
12
+ };
13
+ export type BasicCentraDisplayForSlugCheck = {
14
+ id: number;
15
+ uri: string;
16
+ name: string;
17
+ product: {
18
+ id: number;
19
+ externalId: string;
20
+ };
21
+ productVariants: Array<{
22
+ id: number;
23
+ externalId: string;
24
+ }>;
25
+ };
3
26
  export type BasicCentraProduct = {
4
27
  id: number;
5
28
  name: string;
@@ -154,6 +177,10 @@ export default class CentraHelper extends EnvEngine {
154
177
  getCacheKeyForCentraWarehouse(warehouseExternalId: string): string;
155
178
  getCacheKeyForCentraPricelists(): string;
156
179
  getCacheKeyForCentraPricelist(pricelistExternalId: string): string;
180
+ getCacheKeyForCentraCategory(categoryId: string): string;
181
+ getCacheKeyForCentraCategories(): string;
182
+ getCacheKeyForCentraMeasurementCharts(): string;
183
+ getCacheKeyForCentraMeasurementChart(name: string): string;
157
184
  fetchCountries(iso2Codes?: string[] | undefined | null): Promise<CentraErrors | Array<BasicCentraCountry>>;
158
185
  fetchCentraWarehouses(externalIds?: string[] | undefined | null): Promise<CentraErrors | Array<BasicCentraWarehouse>>;
159
186
  fetchCentraCampaigns(names?: string[] | undefined | null): Promise<CentraErrors | Record<string, BasicCentraCampaign | Error>>;
@@ -174,4 +201,9 @@ export default class CentraHelper extends EnvEngine {
174
201
  getCentraDisplaysByProductIds(centraProductIds: number[]): Promise<Record<string, BasicCentraDisplay[] | Error>>;
175
202
  getCentraVariants(productIds: string[]): Promise<Record<string, BasicCentraVariant | Error>>;
176
203
  static centraSizeNameToSize(centraSizeName: string): string;
204
+ fetchCentraCategories(categoryIds?: string[] | null): Promise<CentraErrors | BasicCentraCategory[]>;
205
+ getCentraCategories(categoryIds?: string[] | null, alwaysFetch?: boolean): Promise<Error | Record<string, Error | BasicCentraCategory>>;
206
+ fetchCentraMeasurementCharts(): Promise<CentraErrors | BasicCentraMeasurementChart[]>;
207
+ getCentraMeasurementCharts(alwaysFetch?: boolean): Promise<Error | Record<string, Error | BasicCentraMeasurementChart>>;
208
+ getCentraDisplaysByUris(uris: string[]): Promise<Record<string, BasicCentraDisplayForSlugCheck[]> | Error>;
177
209
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shushed/helpers",
3
- "version": "0.0.251",
3
+ "version": "0.0.252",
4
4
  "author": "",
5
5
  "license": "UNLICENSED",
6
6
  "description": "",