fix: harden PrestaShop automation jobs

This commit is contained in:
fatequod
2026-08-03 11:20:09 +02:00
parent 5a1e6ffbdd
commit faf1c3ea06
12 changed files with 812 additions and 245 deletions
+65 -19
View File
@@ -4,11 +4,14 @@ const js2xmlparser = require("js2xmlparser");
const NodeCache = require("node-cache");
module.exports = class PrestashopApi {
constructor(shopUrl, apiKey, legacy = true) {
constructor(shopUrl, apiKey, legacy = true, requestOptions = {}) {
this.shopUrl = new URL(shopUrl);
this.apiKey = apiKey;
this.cache = new NodeCache({ stdTTL: 600, checkperiod: 100 });
this.legacy = legacy; // czy używać legacy API (dla PrestaShop < 8)
this.requestTimeoutMs = requestOptions.timeoutMs || 15000;
this.maxGetAttempts = requestOptions.maxGetAttempts || 3;
this.retryBaseMs = requestOptions.retryBaseMs || 250;
}
getUrl(endpoint = "") {
@@ -37,8 +40,9 @@ module.exports = class PrestashopApi {
// @todo przemyśleć czy nie dodac tutaj na sztywno do kazdego zapytania output_format=JSON
let url = this.getUrl(endpoint);
const method = String(metod || 'GET').toUpperCase();
let options = {
method: metod,
method,
headers: {
"Authorization": "Basic " + Buffer.from(this.apiKey + ":").toString("base64"),
'content-type': 'application/xml',
@@ -47,7 +51,7 @@ module.exports = class PrestashopApi {
};
if (data) {
if (metod.toLowerCase() === 'get') {
if (method === 'GET') {
const params = new URLSearchParams(data);
url += (url.includes('?') ? '&' : '?') + params.toString();
} else {
@@ -60,23 +64,58 @@ module.exports = class PrestashopApi {
}
}
try {
let r = await Core.fetch(url, options);
return r.json();
} catch (error) {
// Jeśli allowPartialSuccess jest true i mamy błąd 500, sprawdź czy odpowiedź zawiera użyteczne dane
if (allowPartialSuccess && error.statusCode === 500 && error.response && error.response.body) {
try {
let parsedResponse = JSON.parse(error.response.body);
// Jeśli odpowiedź zawiera dane mimo błędu, zwróć je
if (parsedResponse && typeof parsedResponse === 'object') {
return parsedResponse;
const maxAttempts = method === 'GET' ? this.maxGetAttempts : 1;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
const response = await this.fetchWithTimeout(url, options);
const body = response.text();
let parsed = {};
if (body) {
try {
parsed = JSON.parse(body);
} catch (parseError) {
const error = new Error(`PrestaShop returned invalid JSON (HTTP ${response.status})`);
error.statusCode = response.status;
throw error;
}
} catch (parseError) {
// Jeśli nie można sparsować odpowiedzi, rzuć oryginalny błąd
}
if (response.status < 200 || response.status >= 300) {
if (allowPartialSuccess && response.status === 500 && parsed && typeof parsed === 'object' && Object.keys(parsed).length > 0) {
Log.warn('PrestaShop returned usable data with HTTP 500', { endpoint });
return parsed;
}
const error = new Error(`PrestaShop request failed with HTTP ${response.status}`);
error.statusCode = response.status;
error.responseBody = body.slice(0, 1000);
throw error;
}
return parsed;
} catch (error) {
const retryableStatus = [408, 425, 429].includes(error.statusCode) || error.statusCode >= 500;
const retryable = method === 'GET' && (retryableStatus || !error.statusCode);
if (!retryable || attempt >= maxAttempts) throw error;
await new Promise(resolve => setTimeout(resolve, this.retryBaseMs * (2 ** (attempt - 1))));
}
throw error;
}
}
async fetchWithTimeout(url, options) {
let timer;
try {
return await Promise.race([
Core.fetch(url, options),
new Promise((_, reject) => {
timer = setTimeout(() => {
const error = new Error(`PrestaShop request timed out after ${this.requestTimeoutMs} ms`);
error.code = 'PRESTASHOP_TIMEOUT';
reject(error);
}, this.requestTimeoutMs);
timer.unref?.();
}),
]);
} finally {
clearTimeout(timer);
}
}
@@ -241,8 +280,13 @@ module.exports = class PrestashopApi {
}
}
// PrestaShop image type (not original). home_default ≈ 250×250 in classic theme.
static PRODUCT_IMAGE_TYPE = 'home_default';
getProductImageUrl(productId, imageId) {
const url = this.getUrl('images/products/' + productId + '/' + imageId);
const url = this.getUrl(
'images/products/' + productId + '/' + imageId + '/' + PrestashopApi.PRODUCT_IMAGE_TYPE
);
const sep = url.includes('?') ? '&' : '?';
return url + sep + 'ws_key=' + encodeURIComponent(this.apiKey);
}
@@ -261,7 +305,9 @@ module.exports = class PrestashopApi {
async getProductImageBuffer(productId, imageId) {
let r = await Request({
url: this.getUrl('images/products/' + productId + '/' + imageId),
url: this.getUrl(
'images/products/' + productId + '/' + imageId + '/' + PrestashopApi.PRODUCT_IMAGE_TYPE
),
encoding: null,
headers : { "Authorization" : "Basic " + Buffer.from(this.apiKey + ":").toString("base64") }
});