@sanity/import
Version:
Import documents to a Sanity dataset
43 lines (42 loc) • 1.87 kB
JavaScript
import { extractWithPath } from '@sanity/mutator';
import { deepGet } from './util/deepGet.js';
export async function validateCdrDatasets(docs, options) {
const datasets = getDatasetsFromCrossDatasetReferences(docs);
if (datasets.length === 0) {
return;
}
const { client } = options;
const existing = new Set((await client.datasets.list()).map((dataset)=>dataset.name));
const missing = datasets.filter((dataset)=>!existing.has(dataset));
if (missing.length > 1) {
throw new Error([
`The data to be imported contains one or more cross-dataset references, which refers to datasets that do not exist in the target project.`,
`Missing datasets: ${missing.map((ds)=>`"${ds}"`).join(', ')}`,
'Either create these datasets in the given project, or use the `--skip-cross-dataset-references` flag to skip these references.'
].join('\n'));
}
if (missing.length === 1) {
throw new Error([
`The data to be imported contains one or more cross-dataset references, which refers to a dataset that do not exist in the target project.`,
`Missing dataset: "${missing[0]}"`,
'Either create this dataset in the given project, or use the `--skip-cross-dataset-references` flag to skip these references.'
].join('\n'));
}
}
function getDatasetsFromCrossDatasetReferences(docs) {
const datasets = new Set();
for (const doc of docs){
findCrossCdr(doc, datasets);
}
return [
...datasets
];
}
function findCrossCdr(doc, set) {
const refs = extractWithPath('..[_ref]', doc).map((match)=>deepGet(doc, match.path.slice(0, -1))).filter((ref)=>typeof ref?._dataset === 'string');
for (const ref of refs){
set.add(ref._dataset);
}
return set;
}
//# sourceMappingURL=validateCdrDatasets.js.map