我有一个NodeJS应用程序,该应用程序从远程获取数据,然后将其放入本地数据库中。来自远程的数据非常繁重,因为应该首先计算它们,然后每页发送一次。因此大约需要5分钟。
但是问题是当我触发此函数时,它会在一段时间后触发两次,而不是一次。我真的不明白为什么要这么做。
该应用程序是用Strapi.io构建的
控制器:
module.exports = {
syncProducts: async (ctx) => {
const status = await strapi.services.nav.syncProducts(false);
ctx.send({ status });
},
}
服务:
module.exports = {
syncProducts: async (auto = true) => {
console.log('SYNCING PRODUCTS');
try {
// Gets attributes from remote
const {
warehouseAttributes,
sellableAttributeProducts,
} = await strapi.services["attribute"].getAttributes();
// Gets products from remote
const rProducts = await strapi.services[
"product"
].getProducts();
const existingProducts = await strapi.services.product.find(
{ _limit: -1 },
[]
);
const categories = await strapi.services.category.find(
{ _limit: -1 },
[]
);
const warehouses = await strapi.services.warehouse.find(
{ _limit: -1 },
[]
);
let status = {
created: 0,
updated: 0,
disabled: 0,
reenabled: 0,
};
// FROM REMOTE TO STRAPI
console.log("MAPPING FROM REMOTE TO STRAPI");
for (const item of rProducts) {
await strapi.services["product"].fromRemoteToWeb(
existingProducts,
item,
warehouseAttributes,
sellableAttributeProducts,
warehouses,
categories,
status
);
}
console.log("MAPPING FROM STRAPI TO REMOTE");
for (const item of existingProducts) {
await strapi.services["product"].fromWebToRemote(
rProducts,
item,
sellableAttributeProducts,
status
);
}
return status;
} catch (error) {
console.log(error)
}
},
}
fromRemoteToWeb函数:
module.exports = {
fromRemoteToWeb: async (
existingProducts,
rItem,
warehouseAttributes,
sellableAttributes,
warehouses,
categories,
status
) => {
const existingProduct = existingProducts.filter(
(x) => x.navId === rItem.No
)[0];
const isSellable = await helpers.attributeExists(
sellableAttributes,
rItem.No
);
if (!isSellable) {
return;
}
const itemInWarehouseValue = warehouseAttributes.filter(
(attribute) => attribute.No === rItem.No
);
if (!itemInWarehouseValue || itemInWarehouseValue.length === 0) {
console.log("ITEM HAS NO WAREHOUSE ATTRIBUTE: ", rItem.No);
return;
}
const mappedItemsInWarehouse = helpers.mapWarehouses(
itemInWarehouseValue,
warehouses
);
const category = categories.filter(
(c) => c.code === rItem.category
)[0];
if (!!!existingProduct && isSellable) {
if (!category) {
console.log("NO CATEGORY");
return;
}
// Create new product
try {
status.created++;
await strapi.services.product.create(item);
} catch (error) {
console.log(error);
return;
}
} else if (!!existingProduct && isSellable) {
// Update product
try {
status.updated++;
await strapi.services.product.update(item);
} catch (error) {
console.log(error);
return;
}
} else if (!!existingProduct && !existingProduct.disabled) {
// Disable product
try {
status.disabled++;
await strapi.services.product.update(
{ id: item.id },
{ disabled: true }
);
} catch (error) {
console.log(error);
return;
}
}
},
}
我做错什么了吗? -当我触发控制器时,它会被触发两次。我不知道它是否是因为获取远程数据花费的时间太长并导致超时,或者它是什么。