Last active
May 10, 2020 09:22
-
-
Save kmelve/743b73cfa540415803ab4a9f32c6d849 to your computer and use it in GitHub Desktop.
How to import documents, and add them as a new item in an array of references with Sanity.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* import.js | |
* | |
* Install dependencies: | |
* yarn add p-queue nanoid | |
* or | |
* npm i p-queue nanoid && sanity install | |
* | |
* Run this script with: | |
* sanity exec --with-user-token import.js | |
*/ | |
import client from 'part:@sanity/base/client' | |
import PQueue from 'p-queue' | |
import {customAlphabet as generateId, nanoid} from 'nanoid' | |
import signees from './signees-file.json' | |
const CATEGORY_ID = 'the-_id-to-your-category-document' | |
/** | |
* We use PQueue do prevent hitting the rate limit. | |
* https://www.sanity.io/docs/importing-data | |
*/ | |
const queue = new PQueue({ | |
concurrency: 1, | |
interval: 1000 / 25 | |
}) | |
/** | |
* Loop through the documents, add the signee document, | |
* and append it to the category document’s references array | |
* https://www.sanity.io/docs/js-client | |
*/ | |
signees.forEach(async signee => { | |
let _id = generateId('1234567890abcdefghijklmnopqrstuvwz', 20)() | |
// Add the new document | |
await queue.add(() => client.create({ | |
_id, | |
_type: 'signee', | |
...signee | |
}).then(doc => console.log(`created ${doc._id}`))) | |
// insert a new reference object at the end of the signees array | |
await queue.add(() => client.patch(CATEGORY_ID).insert('after', 'signees[-1]', [ | |
{ _key: nanoid(), _type: 'reference', _ref: _id } | |
]).commit().then(result => console.log(`updated ${result._id}`))) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment