Unlock seamless workflows and faster delivery with our latest releases- get the details

Best practice approach to patching 2,500 documents with 5,000 images in Sanity.io

2 replies
Last updated: Dec 20, 2022
Hi all, just wondering about a best practice approach to patch about 2,500 documents with nearly 5,000 images. As the documents already exist using a patch would normally be the approach. The following example is perfect as the
then
allows me to patch the relevant document with the freshly uploaded image... though I think that'll smash my API usage, so I'm assuming I'd need to amend that to handle Multiple mutations in a transaction ?
Dec 20, 2022, 12:47 PM
Alternatively, I'm wondering whether exporting all documents, merging the image data and then re-import to replace all existing docs may be a lot less intensive on any API's?
Dec 20, 2022, 12:49 PM
Answer was something along the lines of....

let queue = cq()
  .limit({ concurrency: 2 })
  .process((task) => {
    return new Promise(function (resolve, reject) {
      setTimeout(resolve.bind(undefined, task), 1000);
    });
  });

const mutateDocs = async () => {
  // Docs is imported from the file generated by 'generate-relationships.js'
  // Loop through all of the docs returned from our query
  for (const doc of docs) {
    queue(doc).then(async () => {
      // Add a message to help us know the upload is happening
      console.log(`Mutating ${doc?.id}`);
      
      if(doc?.image) {
        fetch(doc?.image)
        .then(res => {
          return res.buffer()
        })
        .then(buffer => {
            return client.assets.upload('image', buffer, {
            filename: doc?.slug,
            title: doc?.name,
          })
        })
        .then(assetDocument => {
          // Here you can decide what to do with the returned asset document. 
          // If you want to set a specific asset field you can to the following:
          return client
            .patch(doc?.related[0])
            .set({
              "media.imageGrid": [
                  {
                    "_type": "figure",
                    "_key": assetDocument._id,
                    "caption": doc?.name,
                    "asset": {
                      "_type": "reference",
                      _ref: assetDocument._id
                    }
                  }
                ]
              })
            .commit()
            .then((updatedDoc) =>
              console.log(`Hurray, updated Entry! ID:`, updatedDoc._id)
            )
            .catch((err) =>
              console.error('Oh no, the Entry update failed: ', err.message)
            );
        });
      }
    });
  }
};

mutateDocs();
Dec 20, 2022, 7:00 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?