Skip to content

Instantly share code, notes, and snippets.

@kmelve
Last active May 10, 2020 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmelve/743b73cfa540415803ab4a9f32c6d849 to your computer and use it in GitHub Desktop.
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
/**
* 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