我一直在努力寻找我无法弄清楚的答案。我正在为 Shopify API 使用 Node.js 模块 microapps .我有一个 JSON 对象,其中包含我需要更新的产品 ID 和 skus 列表,因此我遍历文件并调用调用 api 的函数。 Shopify 的 API 限制对其的调用并发送一个包含剩余值的响应 header 。此 Node 模块提供包含限制和用法的对象。我的问题是基于下面的代码,当我达到限制时如何在 setTimeout 或类似的地方。一旦您进行了第一次调用,它将像这样返回限制对象:
{
remaining: 30,
current: 10,
max: 40
}
这是我在不遵守限制的情况下所拥有的,因为我尝试的一切都失败了:
const products = JSON.parse(fs.readFileSync('./skus.json','utf8'));
for(var i = 0;i < products.length; i++) {
updateProduct(products[i]);
}
function updateProduct(product){
shopify.productVariant.update(variant.id, { sku: variant.sku })
.then(result => cb(shopify.callLimits.remaining))
.catch(err => console.error(err.statusMessage));
}
我知道我需要实现某种回调来检查剩余使用量是否很低,然后等待几秒钟再调用。任何帮助将不胜感激。
最佳答案
我会使用一些东西来限制 shopify-api-node
(Shopify.prototype.request
) 使用的函数的执行速率来创建请求,例如https://github.com/lpinca/valvelet .
下面的代码未经测试,但应该可以工作。它应该遵守每秒 2 次调用的限制。
var Shopify = require('shopify-api-node');
var valvelet = require('valvelet');
var products = require('./skus');
var shopify = new Shopify({
shopName: 'your-shop-name',
apiKey: 'your-api-key',
password: 'your-app-password'
});
// Prevent the private shopify.request method from being called more than twice per second.
shopify.request = valvelet(shopify.request, 2, 1000);
var promises = products.map(function (product) {
return shopify.productVariant.update(product.id, { sku: product.sku });
});
Promise.all(promises).then(function (values) {
// Do something with the responses.
}).catch(function (err) {
console.error(err.stack);
});
关于javascript - 如何使用 microapps Node.js 模块处理 Shopify 的 API 调用限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39539315/