Skip to content

Making product duplicates using the API

Mikk Pristavka edited this page Apr 20, 2017 · 1 revision
// Requires fetch API support

// whitelist of allowed attributes
const allowedKeys = [
  'in_stock',
  'name',
  'price',
  'sku',
  'status',
  'translations',
  'variant_types'
];

// fetch the current product list
fetch('/admin/api/ecommerce/v1/products?include=translations', {
  credentials: 'include'
})
.then(function(response) { return response.json(); })
.then(function(products) {
  // create a duplicate of each product, taking only whitelisted attributes
  products.map(function(product) {
    return allowedKeys.reduce(function(acc, key) {
      acc[key] = product[key];

      // append "(copy)" to each duplicate 
      if (key === 'name') { product[key] += ' (copy)'; }
    }, {});
  })
  // for each duplicate, make a POST request to create it
  .forEach(function(p) {
    fetch('/admin/api/ecommerce/v1/products', {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ product: p })
    });
  });
});