Skip to content

Instantly share code, notes, and snippets.

@kmelve
Created February 12, 2019 21:38
Show Gist options
  • Save kmelve/f86633a4bdf3d44b4cda5e0702b225be to your computer and use it in GitHub Desktop.
Save kmelve/f86633a4bdf3d44b4cda5e0702b225be to your computer and use it in GitHub Desktop.
Sanity: Promote drafts
/* eslint-disable no-console */
import client from 'part:@sanity/base/client'
// Run this script with: `sanity exec --with-user-token migrations/renameField.js`
//
// This example shows how you may write a migration script that sets all drafts to published version
// and deletes the draft version
// This will migrate documents in batches of 100 and continue patching until no more documents are
// returned from the query.
//
// This script can safely be run, even if documents are being concurrently modified by others.
// If a document gets modified in the time between fetch => submit patch, this script will fail,
// but can safely be re-run multiple times until it eventually runs out of documents to migrate.
// A few things to note:
// - This script will exit if any of the mutations fail due to a revision mismatch (which means the
// document was edited between fetch => update)
// - The query must eventually return an empty set, or else this script will continue indefinitely
// Fetching documents that matches the precondition for the migration.
// NOTE: This query should eventually return an empty set of documents to mark the migration
// as complete
const fetchDocuments = () =>
client.fetch(`*[_id in path('drafts.**')][0...100]`)
const buildPatches = docs =>
docs.map(doc => ({
createOrReplace: {
...doc,
_ref: undefined,
_createdAt: undefined,
_id: doc._id.replace('drafts.', '')
},
delete: {
id: doc._id
}
}))
const createTransaction = docs =>
docs.reduce((tx, patch) => tx.createOrReplace({...patch, _id: patch._id.replace('drafts.', '')}).delete(patch._id), client.transaction())
const commitTransaction = tx => tx.commit()
const migrateNextBatch = async () => {
const documents = await fetchDocuments()
if (documents.length === 0) {
console.log('No more documents to migrate!')
return null
}
console.log(
`Migrating batch:\n %s`,
documents.map(doc => `${doc._id} => ${doc._id.replace('drafts.', '')}`).join('\n')
)
const transaction = createTransaction(documents)
await commitTransaction(transaction)
return migrateNextBatch()
}
migrateNextBatch().catch(err => {
console.error(err)
process.exit(1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment