如何使用shopify API批量更新产品元字段

时间:2019-09-12 04:13:20

标签: shopify shopify-app

我想使用Shopify Rest API批量更新产品元字段。

此代码一次仅更新一个元字段。

{
  "metafield": 
      { 
       "namespace": "custom_fields",
        "key": "aa_percentage",
        "value": "2345",
        "value_type": "string"
        }

}

我尝试了这种方法,很抱歉,无法正常工作。

{
  "metafield": 
      { 
       "namespace": "custom_fields",
        "key": "aa_percentage",
        "value": "2345",
        "value_type": "string"
        },
      { 
       "namespace": "custom_fields",
        "key": "cc_percentage",
        "value": "2345",
        "value_type": "string"
        }                           


}

1 个答案:

答案 0 :(得分:0)

此方法无效,因为它不可用。 Shopify文档中没有任何地方对API进行任何批量更新操作。此外,如果您查看API Documentation for Metafields,则一次只能添加,编辑和更新一个元字段。

{
  "metafield": {
    "id": 721389482,
    "value": "something new",
    "value_type": "string"
  }
}

但这并不意味着您必须等待每个调用才能发出下一个更新。您可以同时生成多个更新调用。可以通过多种方式来做到这一点,例如将多个使用者进程或JavaScript中的Promises推入队列。

以下是使用Shopify API Node.js (Official module)的NodeJS中的示例代码。

const Shopify = require('shopify-api-node');

// create a shopify object
const shopify = new Shopify({
    shopName: 'your-shop-name',
    apiKey: 'your-api-key',
    password: 'your-app-password'
});

// define an array with all metafields that need to be updated
const metafieldsData = [{
        namespace: "custom_fields",
        key: "aa_percentage",
        value: "2345",
        value_type: "string"
    },
    {
        namespace: "custom_fields",
        key: "cc_percentage",
        value: "2345",
        value_type: "string"
    }

];

const promises = [];

// push all the requests in an array
metafieldsData.forEach(metafield => {
    promises.push(shopify.metafield
        .create(metafield));
});

// wait for all api calls to finish
Promise.all(promises).then(response => {
    // do whatever with responses
    console.log(response);
});