Praktika · Laikas ir integracijos (P11–P15)

P11 · CRON + lėtas PIM (lygiagretumas)

const pimUrl = initial?.pimBaseUrl;
if (!pimUrl) throw new UserError("Nustatykite PIM URL parametrą");

const products = await rql(`SELECT id, code FROM products WITH companyId = ${companyId} size = 100 WHERE needsPimSync = true`);
const items = products?.content ?? [];
await log.info("Sinchronizuojama prekių: " + items.length);

const tasks = items.map(function (p) {
  return fetchData(undefined, { url: pimUrl + "/product/" + encodeURIComponent(p.code), method: "GET", raw: true })
    .then(function () { return mutate("markProductPimSynced", { productId: p.id }); })
    .catch(function (error) { return log.error(p.code + ": " + error?.message); });
});
await Promise.all(tasks);
output = { message: "PIM sinchronizuota", documentsCount: items.length };

P12 · Ilgas CRON — eilė ir procesoriai

Scenarijuje — loginti trukmę ir skaidyti; konfigūracija „dedikuota eilė“ — operacinė, ne JS.

const t0 = Date.now();
await log.info("CRON start");

// ... darbas ...
await log.info("CRON end, ms=" + (Date.now() - t0));
output = { message: "Baigta", executionStatus: "SUCCESS" };

P13 · 80k įrašų vienu POST (ribos)

// Viešasis REST: scenarijus negali pakeisti partnerio; dokumentuokite puslapiavimą (100 / puslapis)
const PAGE = 100;
let page = 0, total = 0;
while (true) {
  const batch = await fetchData(undefined, {
    url: initial.partnerUrl + "?page=" + page + "&size=" + PAGE,
    method: "GET",
    raw: false
  });
  const arr = JSON.parse(batch.body)?.items ?? [];
  if (arr.length === 0) break;
  for (const row of arr) {
    await mutate("upsertExternalProduct", { row }); // iliustratyvu
    total++;
  }
  if (arr.length < PAGE) break;
  page++;
  await log.info("Importuota iki šiol: " + total);
}
output = { message: "Importuota " + total + " eilučių partijomis", documentsCount: total };

P14 · Webhook audra

const payload = initial?.webhookPayload;
await log.warn("Webhook received: " + JSON.stringify({ type: payload?.type, id: payload?.id }));

try {
  await mutate("processIdempotentWebhook", { dedupeKey: payload.eventKey, payload });
} catch (error) {
  await log.error("Webhook: " + (error?.message ?? error));
  output = { message: "Klaida", executionStatus: "WARNING" };
  return;
}
output = { message: "OK" };

P15 · EDI failas (FTP → fetchData)

const url = initial?.ediFileUrl;
if (!url) throw new UserError("Nėra failo URL");

const file = await fetchData(undefined, { url: url, method: "GET", raw: true });
await log.info("EDI baitų: " + (file.body?.length ?? 0));

try {
  const doc = await dataParser.xmlToJson(file.body);
  await mutate("importEdiPurchaseOrder", { document: doc });
  output = { message: "EDI importuotas", documentsCount: 1 };
} catch (error) {
  await log.error("EDI: " + (error?.message ?? error));
  throw error;
}