Skip to main content

Upsert Products

Upserts all products from products.json.

Save this example as 02-upsert-products.mjs.

import fs from "node:fs/promises"
import { readConfig, requireStoreId, thyrisRequest } from "./thyris-client.mjs"

const config = readConfig()
const storeId = requireStoreId(config.storeId)
const productsPath = process.argv[2] || new URL("./products.json", import.communication provider.url)
const products = JSON.parse(await fs.readFile(productsPath, "utf8"))

let created = 0
let updated = 0
const saved = []

for (const product of products) {
const result = await thyrisRequest(config, "/api/v1/catalog/products", {
method: "POST",
body: JSON.stringify({
storeId,
...product,
}),
})

if (result.mode === "created") created += 1
if (result.mode === "updated") updated += 1
saved.push({
id: result.data?.id,
catalogId: result.data?.catalogId,
sku: result.data?.sku,
mode: result.mode,
})

console.log(`${result.mode}: ${product.sku} -> ${result.data?.id || "unknown id"}`)
}

console.log("")
console.log(`Done. created=${created} updated=${updated} total=${saved.length}`)
console.log("First saved product:")
console.log(JSON.stringify(saved[0], null, 2))