← back to Dw Yolo Loop
artmura-site/create-collection.js
41 lines
#!/usr/bin/env node
/**
* Create (or find) a published smart collection for a DW vendor line, so
* /collections/<handle> resolves on the storefront for the landing's Shop links.
*
* SHOPIFY_ADMIN_TOKEN=… node create-collection.js "<Vendor>" [handle]
*
* Idempotent: if a smart/custom collection with the same title OR handle already
* exists, it prints that one instead of creating a duplicate. Prints the handle to use.
*/
const STORE = process.env.SHOPIFY_STORE || 'designer-laboratory-sandbox.myshopify.com';
const TOKEN = process.env.SHOPIFY_ADMIN_TOKEN;
const API = '2024-10';
const VENDOR = process.argv[2];
const HANDLE = (process.argv[3] || (VENDOR || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''));
if (!TOKEN || !VENDOR) { console.error('usage: SHOPIFY_ADMIN_TOKEN=… node create-collection.js "<Vendor>" [handle]'); process.exit(1); }
const api = (p, opts = {}) => fetch(`https://${STORE}/admin/api/${API}${p}`, {
...opts, headers: { 'X-Shopify-Access-Token': TOKEN, 'Content-Type': 'application/json', ...(opts.headers || {}) },
});
(async () => {
// already exists? (by title across smart+custom)
for (const kind of ['smart_collections', 'custom_collections']) {
const d = await (await api(`/${kind}.json?title=${encodeURIComponent(VENDOR)}`)).json();
const hit = (d[kind] || [])[0];
if (hit) { console.log(`EXISTS ${kind.slice(0,-1)} id=${hit.id} handle=${hit.handle} published=${!!hit.published_at}`); console.log(`USE_HANDLE=${hit.handle}`); return; }
}
const body = { smart_collection: {
title: VENDOR, handle: HANDLE,
body_html: `<p>The <strong>${VENDOR}</strong> collection at Designer Wallcoverings — to the trade.</p>`,
sort_order: 'created-desc', published: true, disjunctive: false,
rules: [{ column: 'vendor', relation: 'equals', condition: VENDOR }],
}};
const res = await api('/smart_collections.json', { method: 'POST', body: JSON.stringify(body) });
const d = await res.json();
if (!d.smart_collection) { console.error('ERR', res.status, JSON.stringify(d)); process.exit(1); }
console.log(`CREATED smart_collection id=${d.smart_collection.id} handle=${d.smart_collection.handle} published=${!!d.smart_collection.published_at}`);
console.log(`USE_HANDLE=${d.smart_collection.handle}`);
})().catch(e => { console.error(e); process.exit(1); });