This repository has been archived by the owner on Apr 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
normalizeAllBlocks.js
79 lines (71 loc) · 2.11 KB
/
normalizeAllBlocks.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
75
76
77
78
79
// This will normalize every block in your dataset. For instance if you regret allowing a special decorator.
// Put on the studio root folder and run with SANITY_TOKEN=XXX npx node ./normalizeBlocks.js
// Could be used as an inspiration to migrate some type in your dataset, not just blocks.
const sanityClient = require("@sanity/client");
const { normalizeBlock } = require("@sanity/block-tools");
const { extractWithPath } = require("@sanity/mutator");
const config = require("./sanity.json");
const sanityToken = process.env.SANITY_TOKEN
if (!sanityToken) {
throw new Error('No Sanity token found. Set with env var SANITY_TOKEN=xxxx')
}
// Act on all documents
const query = "*[]";
// Adjust the decorators to the set you want to allow
const allowedDecaorators = [
"strong",
"em",
"code",
"underline",
"strike-through",
"sub",
"sup"
];
const client = sanityClient({
projectId: config.api.projectId,
dataset: config.api.dataset,
useCdn: false,
token: sanityToken
});
function convertPath(pathArr) {
return pathArr
.map(part => {
if (Number.isInteger(part)) {
return `[${part}]`;
}
return `.${part}`;
})
.join("")
.substring(1);
}
client.fetch(query).then(results => {
const patchedDocuments = [];
results.forEach(async result => {
const matches = extractWithPath('..[_type=="block"]', result);
let patch = client.patch(result._id);
matches.forEach(match => {
const block = match.value;
const path = convertPath(match.path);
const normalizedBlock = normalizeBlock(block, { allowedDecaorators });
const patchData = { [path]: normalizedBlock };
patch = patch.set(patchData);
});
const patchLength = patch.operations.set
? Object.keys(patch.operations.set).length
: 0;
if (patchLength > 0) {
patchedDocuments.push(result._id);
await patch.commit();
console.log(
`Patched ${patchLength} blocks in document ${result._id}`
);
}
});
console.log(
`Patched ${patchedDocuments.length} documents with ids: ${JSON.stringify(
patchedDocuments,
null,
2
)}`
);
});