Structured Content 2022: Join our conference to explore fresh perspectives on content and digital experiences →

Create A Document for All Current Project Users

By Racheal Pennell & Geoff Ball

If you'd like to be able to reference your project users within your content, you'll need to create a document for them.

createUserDocuments.js

import client from "part:@sanity/base/client"
import cq from 'concurrent-queue'
import userStore from 'part:@sanity/base/user'

const studioClient = client.withConfig({apiVersion: '2021-03-25'})

// Create a queue to limit the rate at which you write changes to Sanity
let queue = cq().limit({ concurrency: 2 }).process(function (task) {
  return new Promise(function (resolve, reject) {
      setTimeout(resolve.bind(undefined, task), 1000)
  })
})

const createUserDocuments = async () => {
  //query for all members, then use the userStore to get their details
  const allUsers = await studioClient
    .fetch(`*[_id in path('_.groups.*')].members[@ != 'everyone']`)
    .then(res => userStore.getUsers(res))
    .then(users => users.filter(user => user.isCurrentUser))

    for (const user of allUsers){
      const doc = {
        _type: 'person',
        _id: user.id, 
        //other fields you have in your schema
      }
      queue(doc).then(async () => {
        //create the doc via the client
        studioClient.create(doc)
          .then(updatedDoc => {
            console.log(`Hurray, the doc is updated! New document:${updatedDoc._id}`)
          })
          .catch((err) => {
            console.error('Oh no, the update failed: ', err.message)
          })
      })
    }
 
}



createUserDocuments()

// execute this script by running 
// $ sanity exec ./path-to-your-script --withUserToken --mock-browser-env

Initial Value Example

{
  name: 'author',
  type: 'reference',
  to: [{ type: 'person' }],
  initialValue:  async () => {
    const currentUser = await userStore.getCurrentUser()

    return {
      _type: 'reference',
      _ref: currentUser.id
    }
  }
 },

By using the id specified in the userStore as the _id of the document you're creating, you'll be able to use the userStore throughout your Studio to populate things like initial values.

Contributors

Other schemas by authors