fix(prestashop): poll orders every minute in release 1.1.7
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
const PrestashopApi = require('../../src/PrestaApi');
|
||||
const { isLegacyApi } = require('../../src/utils');
|
||||
const { loadConfig, isConfigured } = require('../../src/module-config');
|
||||
const { PERMISSIONS, requirePermission } = require('../../src/register-permissions');
|
||||
const { findMetadataBySourceAndSku } = require('../../src/product-metadata');
|
||||
|
||||
const MAX_PRODUCTS = 100;
|
||||
const METADATA_CONCURRENCY = 5;
|
||||
|
||||
function normalizeRequestProduct(value) {
|
||||
const sourceId = String(value?.sourceId ?? '').trim();
|
||||
const sku = String(value?.sku ?? '').trim();
|
||||
if (!sourceId || !sku) return null;
|
||||
return { sourceId, sku };
|
||||
}
|
||||
|
||||
function uniqueProducts(products) {
|
||||
const seen = new Set();
|
||||
const result = [];
|
||||
for (const value of Array.isArray(products) ? products : []) {
|
||||
const product = normalizeRequestProduct(value);
|
||||
if (!product) continue;
|
||||
const key = `${product.sourceId}\u0000${product.sku.toUpperCase()}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
result.push(product);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function mapWithConcurrency(values, concurrency, worker) {
|
||||
let nextIndex = 0;
|
||||
const runners = Array.from({ length: Math.min(concurrency, values.length) }, async () => {
|
||||
while (nextIndex < values.length) {
|
||||
const index = nextIndex++;
|
||||
await worker(values[index], index);
|
||||
}
|
||||
});
|
||||
await Promise.all(runners);
|
||||
}
|
||||
|
||||
module.exports = async function(params, ctx) {
|
||||
requirePermission(PERMISSIONS.ORDERS_VIEW, ctx);
|
||||
|
||||
const products = uniqueProducts(params?.products);
|
||||
if (products.length === 0) return { results: [] };
|
||||
if (products.length > MAX_PRODUCTS) throw new Error('products exceeds the 100 item limit');
|
||||
|
||||
const config = await loadConfig();
|
||||
if (!isConfigured(config)) return { results: [] };
|
||||
|
||||
const api = new PrestashopApi(config.apiUrl, config.apiKey, isLegacyApi(config.versionCode));
|
||||
const results = new Array(products.length);
|
||||
await mapWithConcurrency(products, METADATA_CONCURRENCY, async (product, index) => {
|
||||
try {
|
||||
const metadata = await findMetadataBySourceAndSku(api, product);
|
||||
if (metadata) results[index] = { ...product, ...metadata };
|
||||
} catch (_) { /* one product must not block the remaining metadata batch */ }
|
||||
});
|
||||
|
||||
return { results: results.filter(Boolean) };
|
||||
};
|
||||
|
||||
module.exports._private = { MAX_PRODUCTS, METADATA_CONCURRENCY, uniqueProducts, mapWithConcurrency };
|
||||
Reference in New Issue
Block a user