-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpatch.js
74 lines (65 loc) · 2.47 KB
/
patch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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 renames a field (name => fullname)
// on a specific document type (author).
// 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(
`*[_type == 'hymn' && defined(files) && references(*[file match 'ppt*']._id)][0...100] {..., "followFiles": files[]->}`
);
const buildPatches = docs =>
docs.map(doc => {
return {
id: doc._id,
patch: {
unset: doc.followFiles
.filter(elem => {
return elem.name.includes('ppt');
})
.map(item => `files[_ref=="${item._id}"]`),
// This will cause the migration to fail if any of the documents has been
// modified since it was fetched.
ifRevisionID: doc._rev
}
};
});
const createTransaction = patches =>
patches.reduce(
(tx, patch) => tx.patch(patch.id, patch.patch),
client.transaction()
);
const commitTransaction = tx => tx.commit();
const migrateNextBatch = async () => {
const documents = await fetchDocuments();
const patches = buildPatches(documents);
if (patches.length === 0) {
console.log('No more documents to migrate!');
return null;
}
console.log(
`Migrating batch:\n %s`,
patches
.map(patch => `${patch.id} => ${JSON.stringify(patch.patch)}`)
.join('\n')
);
const transaction = createTransaction(patches);
await commitTransaction(transaction);
return migrateNextBatch();
};
migrateNextBatch().catch(error => {
console.error(error);
process.exit(1);
});