← back to Dw Image Shrink

enum-metaobject-refs.js

29 lines

// Collect file gids referenced by metaobjects (found: shopify--color-pattern.image
// = storefront color-swatch images). These are REFERENCED files and must be
// excluded from the orphan list. Writes referenced-file-gids.txt (numeric gids).
import fs from 'fs';
import https from 'https';
const SHOP='designer-laboratory-sandbox.myshopify.com';
const TOK=fs.readFileSync('/Users/macstudio3/Projects/secrets-manager/.env','utf8').split('\n').find(l=>l.startsWith('SHOPIFY_CONTENT_TOKEN=')).split('=').slice(1).join('=').replace(/["' ]/g,'');
const DIR='/Users/macstudio3/Projects/dw-image-shrink';
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
function gql(query){return new Promise((res,rej)=>{const body=JSON.stringify({query});const req=https.request({method:'POST',host:SHOP,path:'/admin/api/2024-10/graphql.json',headers:{'X-Shopify-Access-Token':TOK,'Content-Type':'application/json','Content-Length':Buffer.byteLength(body)}},r=>{let d='';r.on('data',c=>d+=c);r.on('end',()=>{try{res(JSON.parse(d))}catch(e){res({errors:[{message:d.slice(0,120)}]})}});});req.on('error',rej);req.write(body);req.end();});}
// enumerate ALL metaobject types (defensive) that have a file_reference; here we
// sweep every type and pull any field whose value looks like a file gid.
const TYPES=['shopify--color-pattern'];
const gids=new Set();
for(const type of TYPES){
  let cursor=null,n=0;
  while(true){
    const q=`{ metaobjects(first:200, type:"${type}"${cursor?`, after:"${cursor}"`:''}){ pageInfo{hasNextPage endCursor} edges{ node{ id fields{ key value reference{ __typename ... on MediaImage{id} ... on GenericFile{id} ... on Video{id} } } } } } }`;
    let r; for(let a=0;a<6;a++){ r=await gql(q); if(r.errors&&/throttl/i.test(JSON.stringify(r.errors))){await sleep(1500);continue;} break; }
    if(r.errors){ console.error(type,'ERR',JSON.stringify(r.errors).slice(0,140)); break; }
    const conn=r.data.metaobjects;
    for(const e of conn.edges){ n++; for(const f of e.node.fields){ if(f.reference&&f.reference.id) gids.add(f.reference.id.split('/').pop()); else if(f.value&&/^gid:\/\/shopify\/(MediaImage|GenericFile|Video)\//.test(f.value)) gids.add(f.value.split('/').pop()); } }
    if(!conn.pageInfo.hasNextPage) break; cursor=conn.pageInfo.endCursor; await sleep(120);
  }
  console.log(`${type}: ${n} entries scanned`);
}
fs.writeFileSync(DIR+'/referenced-file-gids.txt',[...gids].join('\n'));
console.log(`DONE: ${gids.size} metaobject-referenced file gids → referenced-file-gids.txt`);