← back to Dw Unbuyable Recovery Pilot

tk11252-hollywood/undo-remove-variants.mjs

19 lines

#!/usr/bin/env node
// UNDO for TK-11252: delete every variant recorded in created.json.
import fs from 'node:fs';
const TOK = fs.readFileSync(process.env.HOME+'/Projects/secrets-manager/.env','utf8')
  .split('\n').find(l=>l.startsWith('SHOPIFY_ADMIN_TOKEN=')).split('=').slice(1).join('=').trim();
const SHOP='designer-laboratory-sandbox.myshopify.com', API='2024-10';
const APPLY = process.argv.includes('--apply');
const created = JSON.parse(fs.readFileSync(new URL('./created.json',import.meta.url),'utf8'));
const M=`mutation($productId: ID!, $variantsIds: [ID!]!){ productVariantsBulkDelete(productId:$productId, variantsIds:$variantsIds){ userErrors{field message} } }`;
for (const c of created){
  if(!APPLY){ console.log(`DRY delete ${c.variant_id} (${c.sku})`); continue; }
  const r=await fetch(`https://${SHOP}/admin/api/${API}/graphql.json`,{method:'POST',
    headers:{'X-Shopify-Access-Token':TOK,'Content-Type':'application/json'},
    body:JSON.stringify({query:M,variables:{productId:`gid://shopify/Product/${c.pid}`,variantsIds:[c.variant_id]}})});
  const j=await r.json();
  console.log(`${j.data?.productVariantsBulkDelete?.userErrors?.length? 'FAIL':'OK  '} delete ${c.variant_id} (${c.sku})`);
  await new Promise(s=>setTimeout(s,300));
}