Using the CLI for mutations in Sanity and resolving a permissions issue.

8 replies
Last updated: Nov 10, 2021
Hi all. Just starting out playing with sanity, and I really like the Vision plugin so I have a nice UI for running queries. I know I can’t do mutations here … but is there an easy way to do them from the CLI command? Or do I have to make a small JS script using the client for each one?
Nov 10, 2021, 4:03 PM
Hey User! You can see some example of using the CLI for mutations here .
Nov 10, 2021, 6:58 PM
Thanks
user M
… I was actually using the sample from here as a starting point, since I’m trying to subtract 60 days from a datetime field for all my documents (and I don’t think the
dec
mutation will work there?)
Nov 10, 2021, 7:03 PM
What I have:
import sanityClient from 'part:@sanity/base/client'
const client = sanityClient.withConfig({
  apiVersion: '2021-11-01',
})


const fetchDocuments = () =>
  client.fetch(`*[_type == 'deal']{_id, title, publishedDate}[0..1]`)

const buildPatches = docs => {
  return docs.map(doc => {
    console.log(doc.title);
    const pubDate = new Date(doc.publishedDate);
    pubDate.setDate( pubDate.getDate() - 60 );
    return {
      id: doc._id,
      patch: {
        set: {
          publishedDate: pubDate
        }
      }
    }
  })
}

const createTransaction = patches =>
  patches.reduce((tx, patch) => tx.patch(patch.id, patch.patch), client.transaction())

const commitTransaction = tx => tx.commit()

const migrate = async () => {
  const documents = await fetchDocuments()
  const patches = buildPatches(documents)
  console.log(
    `Migrating batch:\n %s`,
    patches.map(patch => `${patch.id} => ${JSON.stringify(patch.patch)}`).join('\n')
  )
  const transaction = createTransaction(patches)
  return await commitTransaction(transaction)
}

migrate().catch(err => {
  console.error(err)
  process.exit(1)
})
Nov 10, 2021, 7:04 PM
Ah, from your question, I thought you were looking for an option besides the JS client.
Nov 10, 2021, 7:05 PM
I was … but that would only work for “non-dynamic” changes, I suppose, right? i.e. if I can define the change I want in a static string (as opposed to something like changing a value based on some other condition).
Nov 10, 2021, 7:06 PM
In any case, I think I’m just up against a permissions issue now. I started a thread here … if you have any ideas!
Nov 10, 2021, 7:07 PM
Yeah, exactly. If you need to use JS to compute something this is the way to go. I think you may want to use the date fns package to perform your subtraction here.
Nov 10, 2021, 7:08 PM
Re your permissions issue, can you DM me your project ID so that I can check your permissions on the backend?
Nov 10, 2021, 7:09 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?