Skip to content

Instantly share code, notes, and snippets.

@runeb
Last active February 25, 2023 02:37
Show Gist options
  • Save runeb/e37f23aea79867752bc3a6f2c86b3db1 to your computer and use it in GitHub Desktop.
Save runeb/e37f23aea79867752bc3a6f2c86b3db1 to your computer and use it in GitHub Desktop.
Patch Sanity documents from one dataset to another
// Example of how to patch documents in a dataset with data from another dataset
// using the Sanity client and transactions. More info: https://www.sanity.io/docs/transactions
import {createClient} from '@sanity/client'
// The 'from' dataset
const source = createClient({
projectId: 'rwmuledy',
dataset: 'production',
useCdn: false,
token: 'skseugwsW...',
})
// The 'to' dataset, reuse the config from the source dataset but change the
// dataset. Can also use a different project, token etc of course.
const destination = createClient({
...source.config(),
dataset: 'other',
})
// Max size of a transaction we will create, 3.5MB
const MAX_SIZE = 3500000
const run = async () => {
// Query the source dataset and build up a transaction of createIfNotExists
// and patch mutations
let transaction = destination.transaction()
// Get all documents with a title from the source dataset
// Change this query to match your needs
const result = await await source.fetch(`*[ defined(title) ] {_id, _type, title}`)
for (const row of result) {
// Make sure the document exists in the destination dataset, that is why
// we included _type in the query projection
transaction.createIfNotExists(row)
// Patch the document in the other dataset with the title from the source
// dataset, in case the document already existed
transaction.patch(row._id, {
set: {title: row.title}, // Also change this to match your needs
})
// If the transaction built up so far is larger than the MAX_SIZE, commit
// early to avoid the transaction getting too large (max 4MB)
const txSize = Buffer.byteLength(JSON.stringify(transaction.toJSON()))
if (txSize >= MAX_SIZE) {
const result = await transaction.commit()
console.log(result)
// Start a new transaction for the next batch
transaction = destination.transaction()
}
}
// Commit the transaction, which will create the documents and/or patch them
// in the destination dataset.
transaction.commit().then(console.log)
}
// Just to get around the top-level await
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment