-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorageClient.js
363 lines (316 loc) · 10.2 KB
/
StorageClient.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import { callPreviewPublish } from '../../utils/admin.js';
import { BatchProcessor } from '../../utils/batch.js';
import { errorWithResponse } from '../../utils/http.js';
export default class StorageClient {
/**
* @param {Context} ctx
* @returns {StorageClient}
*/
static fromContext(ctx) {
if (!ctx.attributes.storageClient) {
ctx.attributes.storageClient = new StorageClient(ctx);
}
return ctx.attributes.storageClient;
}
/** @type {Context} */
ctx = undefined;
/**
* @param {Context} ctx
*/
constructor(ctx) {
this.ctx = ctx;
}
/** @type {Config} */
get config() {
return this.ctx.config;
}
/**
* Load product by SKU.
* @param {string} sku - The SKU of the product.
* @returns {Promise<ProductBusEntry>} - A promise that resolves to the product.
*/
async fetchProduct(sku) {
const {
log,
env,
config: {
org,
site,
storeCode,
storeViewCode,
},
} = this.ctx;
const key = `${org}/${site}/${storeCode}/${storeViewCode}/products/${sku}.json`;
log.debug('Fetching product from R2:', key);
const object = await env.CATALOG_BUCKET.get(key);
if (!object) {
// Product not found in R2
throw errorWithResponse(404, 'Product not found');
}
const productData = await object.json();
return productData;
}
/**
* Save products in batches
*
* @param {ProductBusEntry[]} products - The products to save.
* @returns {Promise<Partial<BatchResult>[]>} - Resolves with an array of save results.
*/
async saveProducts(products) {
const processor = new BatchProcessor(this.ctx, (batch) => this.storeProductsBatch(batch));
const saveResults = await processor.process(products);
this.ctx.log.info(`Completed saving ${products.length} products.`);
return saveResults;
}
/**
* Handler function to process a batch of products.
* @param {ProductBusEntry[]} batch - An array of products to save.
* @returns {Promise<Partial<BatchResult>[]>} - Resolves with an array of save results.
*/
async storeProductsBatch(batch) {
const {
env,
log,
config: {
org,
site,
storeCode,
storeViewCode,
},
} = this.ctx;
const storePromises = batch.map(async (product) => {
const { sku, title, urlKey } = product;
const key = `${org}/${site}/${storeCode}/${storeViewCode}/products/${sku}.json`;
const body = JSON.stringify(product);
try {
const customMetadata = { sku, title };
if (urlKey) {
customMetadata.urlKey = urlKey;
}
// Attempt to save the product
await env.CATALOG_BUCKET.put(key, body, {
httpMetadata: { contentType: 'application/json' },
customMetadata,
});
// If urlKey exists, save the urlKey metadata
if (urlKey) {
const metadataKey = `${org}/${site}/${storeCode}/${storeViewCode}/urlkeys/${urlKey}`;
await env.CATALOG_BUCKET.put(metadataKey, '', {
httpMetadata: { contentType: 'text/plain' },
customMetadata,
});
}
const adminResponse = await callPreviewPublish(this.config, 'POST', sku, urlKey);
/**
* @type {Partial<BatchResult>}
*/
const result = {
sku,
message: 'Product saved successfully.',
...adminResponse.paths,
};
return result;
} catch (error) {
log.error(`Error storing product SKU: ${sku}:`, error);
return {
sku,
status: error.code || 500,
message: `Error: ${error.message}`,
};
}
});
const batchResults = await Promise.all(storePromises);
return batchResults;
}
/**
* Deletes multiple products by their SKUs in batches while tracking each deletion's response.
* @param {string[]} skus - An array of SKUs of the products to delete.
* @returns {Promise<Partial<BatchResult>[]>} - Resolves with an array of deletion results.
* @throws {Error} - Throws an error if the input parameters are invalid.
*/
async deleteProducts(skus) {
const { log } = this.ctx;
const processor = new BatchProcessor(this.ctx, (batch) => this.deleteProductsBatch(batch));
const deleteResults = await processor.process(skus);
log.info(`Completed deletion of ${skus.length} products.`);
return deleteResults;
}
/**
* Handler function to process a batch of SKUs for deletion.
* @param {string[]} batch - An array of SKUs to delete.
* @returns {Promise<Partial<BatchResult>[]>} - Resolves with an array of deletion results.
*/
async deleteProductsBatch(batch) {
const {
log,
env,
config: {
org,
site,
storeCode,
storeViewCode,
},
} = this.ctx;
const deletionPromises = batch.map(async (sku) => {
try {
const productKey = `${org}/${site}/${storeCode}/${storeViewCode}/products/${sku}.json`;
const productHead = await env.CATALOG_BUCKET.head(productKey);
if (!productHead) {
log.warn(`Product with SKU: ${sku} not found. Skipping deletion.`);
return {
sku,
statusCode: 404,
message: 'Product not found.',
};
}
const { customMetadata } = productHead;
await env.CATALOG_BUCKET.delete(productKey);
const { urlKey } = customMetadata;
if (urlKey) {
const urlKeyPath = `${org}/${site}/${storeCode}/${storeViewCode}/urlkeys/${urlKey}`;
await env.CATALOG_BUCKET.delete(urlKeyPath);
}
const adminResponse = await callPreviewPublish(this.ctx.config, 'DELETE', sku, urlKey);
/**
* @type {Partial<BatchResult>}
*/
const result = {
sku,
message: 'Product deleted successfully.',
...adminResponse.paths,
};
return result;
} catch (error) {
log.error(`Failed to delete product with SKU: ${sku}. Error: ${error.message}`);
return {
sku,
status: error.code || 500,
message: `Error: ${error.message}`,
};
}
});
const batchResults = await Promise.all(deletionPromises);
return batchResults;
}
/**
* Resolve SKU from a URL key.
* @param {string} urlKey - The URL key.
* @returns {Promise<string>} - A promise that resolves to the SKU.
*/
async lookupSku(urlKey) {
const {
env,
config: {
org,
site,
storeCode,
storeViewCode,
},
} = this.ctx;
// Make a HEAD request to retrieve the SKU from metadata based on the URL key
const urlKeyPath = `${org}/${site}/${storeCode}/${storeViewCode}/urlkeys/${urlKey}`;
const headResponse = await env.CATALOG_BUCKET.head(urlKeyPath);
if (!headResponse || !headResponse.customMetadata?.sku) {
// SKU not found for the provided URL key
throw errorWithResponse(404, 'Product not found');
}
// Return the resolved SKU
return headResponse.customMetadata.sku;
}
/**
* Resolve URL key from a SKU.
* @param {string} sku - The SKU of the product.
* @returns {Promise<string | undefined>} - A promise that resolves to the URL key or undefined.
*/
async lookupUrlKey(sku) {
const {
env,
config: {
org,
site,
storeCode,
storeViewCode,
},
} = this.ctx;
// Construct the path to the product JSON file
const productKey = `${org}/${site}/${storeCode}/${storeViewCode}/products/${sku}.json`;
const headResponse = await env.CATALOG_BUCKET.head(productKey);
if (!headResponse || !headResponse.customMetadata) {
return undefined;
}
const { urlKey } = headResponse.customMetadata;
if (!urlKey) {
return undefined;
}
return urlKey;
}
/**
* List all products from R2.
* TODO: Setup pagination
* @returns {Promise<ProductBusEntry[]>} - A promise that resolves to the products.
*/
async listAllProducts() {
const {
env,
config: {
org,
site,
storeCode,
storeViewCode,
},
} = this.ctx;
const listResponse = await env.CATALOG_BUCKET.list({
prefix: `${org}/${site}/${storeCode}/${storeViewCode}/products/`,
});
const files = listResponse.objects;
const batchSize = 50;
const customMetadataArray = [];
// Helper function to split the array into chunks of a specific size
function chunkArray(array, size) {
const result = [];
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size));
}
return result;
}
const fileChunks = chunkArray(files, batchSize);
// Process each chunk sequentially
for (const chunk of fileChunks) {
// eslint-disable-next-line no-await-in-loop
const chunkResults = await Promise.all(
chunk.map(async (file) => {
const objectKey = file.key;
const headResponse = await env.CATALOG_BUCKET.head(objectKey);
if (headResponse) {
const { customMetadata } = headResponse;
const { sku } = customMetadata;
return {
...customMetadata,
links: {
product: `${this.ctx.url.origin}/${org}/${site}/catalog/${storeCode}/${storeViewCode}/product/${sku}`,
},
};
} else {
return {
fileName: objectKey,
};
}
}),
);
// Append the results of this chunk to the overall results array
customMetadataArray.push(...chunkResults);
}
return customMetadataArray;
}
}