← back to Majilite Onboard

scripts/set_collection_image.js

28 lines

const fs=require('fs'),path=require('path');
const STORE='designer-laboratory-sandbox.myshopify.com';
const TOKEN=(fs.readFileSync(path.join(process.env.HOME,'Projects/secrets-manager/.env'),'utf8').match(/^SHOPIFY_ADMIN_TOKEN=(.+)$/m)||[])[1].replace(/["']/g,'').trim();
const GQL=`https://${STORE}/admin/api/2024-10/graphql.json`;
const COLLECTION='gid://shopify/Collection/303540666419';
async function gql(q,v){const r=await fetch(GQL,{method:'POST',headers:{'X-Shopify-Access-Token':TOKEN,'Content-Type':'application/json'},body:JSON.stringify({query:q,variables:v})});const j=await r.json();if(j.errors)throw new Error(JSON.stringify(j.errors).slice(0,200));return j.data;}
(async()=>{
  // pick a rich gold swatch as cover
  const prods=JSON.parse(fs.readFileSync(path.join(__dirname,'..','data/products.json'),'utf8'));
  const cover=prods.find(p=>/Stature Gold/i.test(p.title))||prods.find(p=>p.color_family==='Gold')||prods[0];
  const file=path.join(__dirname,'..','public',cover.image);
  console.log('cover swatch:',cover.dw_sku,cover.title);
  // staged upload
  const su=await gql(`mutation($input:[StagedUploadInput!]!){ stagedUploadsCreate(input:$input){ stagedTargets{ url resourceUrl parameters{name value} } userErrors{message} } }`,
    {input:[{filename:cover.dw_sku+'.png',mimeType:'image/png',resource:'COLLECTION_IMAGE',httpMethod:'POST'}]});
  const t=su.stagedUploadsCreate.stagedTargets[0];
  const form=new FormData();
  for(const p of t.parameters) form.append(p.name,p.value);
  form.append('file', new Blob([fs.readFileSync(file)],{type:'image/png'}), cover.dw_sku+'.png');
  const up=await fetch(t.url,{method:'POST',body:form});
  if(!(up.status>=200&&up.status<300)) throw new Error('upload '+up.status);
  // set collection image
  const d=await gql(`mutation($input:CollectionInput!){ collectionUpdate(input:$input){ collection{ id image{ url } } userErrors{field message} } }`,
    {input:{id:COLLECTION, image:{src:t.resourceUrl, altText:'Majilite Metallic Specialties I — '+cover.title}}});
  const ue=d.collectionUpdate.userErrors;
  console.log(ue&&ue.length?('userErrors '+JSON.stringify(ue)):('cover set → '+(d.collectionUpdate.collection.image||{}).url));
})();