89 lines
2.5 KiB
JavaScript
89 lines
2.5 KiB
JavaScript
/**
|
|
* Patch `product.abiirPdp` on Sanity `product` documents (Shopify sync) by handle.
|
|
*
|
|
* Usage (from Hydrogen/web):
|
|
* cp scripts/pdp-seed.example.json scripts/pdp-seed.json
|
|
* # edit handles + copy
|
|
* node --env-file=.env ./scripts/sanity-seed-pdp.mjs scripts/pdp-seed.json
|
|
*
|
|
* Requires SANITY_API_WRITE_TOKEN with mutate on `product`.
|
|
*/
|
|
|
|
import {readFileSync, existsSync} from 'node:fs';
|
|
import {resolve} from 'node:path';
|
|
import {createClient} from '@sanity/client';
|
|
|
|
function req(name) {
|
|
const v = process.env[name];
|
|
if (!v || !String(v).trim()) {
|
|
console.error(`Missing required env: ${name}`);
|
|
process.exit(1);
|
|
}
|
|
return String(v).trim();
|
|
}
|
|
|
|
const projectId = req('SANITY_PROJECT_ID');
|
|
const dataset = req('SANITY_DATASET');
|
|
const token = req('SANITY_API_WRITE_TOKEN');
|
|
const apiVersion = process.env.SANITY_API_VERSION?.trim() || '2026-04-16';
|
|
|
|
const client = createClient({
|
|
projectId,
|
|
dataset,
|
|
apiVersion,
|
|
token,
|
|
useCdn: false,
|
|
});
|
|
|
|
async function patchHandle(handle, abiirPdp) {
|
|
const id = await client.fetch(
|
|
`*[_type == "product" && store.slug.current == $h][0]._id`,
|
|
{h: handle},
|
|
);
|
|
if (!id) {
|
|
console.warn(`SKIP "${handle}": no product document (sync product from Shopify first).`);
|
|
return false;
|
|
}
|
|
await client.patch(id).set({abiirPdp}).commit();
|
|
console.log(`OK "${handle}" → ${id}`);
|
|
return true;
|
|
}
|
|
|
|
async function main() {
|
|
const jsonPath = resolve(process.argv[2] || 'scripts/pdp-seed.json');
|
|
if (!existsSync(jsonPath)) {
|
|
console.error(`File not found: ${jsonPath}`);
|
|
console.error('Copy scripts/pdp-seed.example.json to scripts/pdp-seed.json or pass a path.');
|
|
process.exit(1);
|
|
}
|
|
|
|
const parsed = JSON.parse(readFileSync(jsonPath, 'utf8'));
|
|
const byHandle = parsed.byHandle ?? parsed;
|
|
if (typeof byHandle !== 'object' || byHandle === null) {
|
|
console.error('JSON must have top-level { "byHandle": { "handle": { ...abiirPdp } } }');
|
|
process.exit(1);
|
|
}
|
|
|
|
const entries = Object.entries(byHandle);
|
|
if (entries.length === 0) {
|
|
console.error('No handles in byHandle');
|
|
process.exit(1);
|
|
}
|
|
|
|
let ok = 0;
|
|
for (const [handle, abiirPdp] of entries) {
|
|
if (!handle?.trim() || typeof abiirPdp !== 'object' || abiirPdp === null) {
|
|
console.warn(`SKIP invalid entry: ${handle}`);
|
|
continue;
|
|
}
|
|
if (await patchHandle(handle.trim(), abiirPdp)) ok += 1;
|
|
}
|
|
|
|
console.log(`\nDone. Patched ${ok}/${entries.length} product(s).`);
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|