← back to Dw Sarah Rowland Searchfix

lib.mjs

35 lines

// Shared helpers for the Sarah Rowland search-fix (TK-10037)
// Reads the LIVE store (designer-laboratory-sandbox) — treat every write as production.
import fs from 'node:fs';
import os from 'node:os';

const ENV_PATH = `${os.homedir()}/Projects/secrets-manager/.env`;

export function getToken() {
  const env = fs.readFileSync(ENV_PATH, 'utf8');
  const m = env.match(/^SHOPIFY_ADMIN_TOKEN=(.+)$/m);
  if (!m) throw new Error('SHOPIFY_ADMIN_TOKEN not found in secrets .env');
  return m[1].trim();
}

export const STORE = 'designer-laboratory-sandbox.myshopify.com';
export const API = '2024-10';

export async function gql(query, variables = {}) {
  const res = await fetch(`https://${STORE}/admin/api/${API}/graphql.json`, {
    method: 'POST',
    headers: {
      'X-Shopify-Access-Token': getToken(),
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ query, variables }),
  });
  const json = await res.json();
  if (json.errors) throw new Error('GraphQL errors: ' + JSON.stringify(json.errors));
  if (json.data && Object.values(json.data).some(v => v && v.userErrors && v.userErrors.length))
    throw new Error('userErrors: ' + JSON.stringify(json.data));
  return json.data;
}

export const HANDLE = 'sarah-rowland-wallpaper-collection';