Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Clarification on creating drafts from a published document in Sanity.io.

7 replies
Last updated: Dec 14, 2023
A couple questions on creating drafts from 3rd party.
I have a app where I want to change the state of a published document to draft so that someone has to go in and publish from the studio.

If I use
createIfNotExist
does that just create a new draft that is a new document unrelated to the published document I am trying to change to a draft state? As far as I am aware, I cannot
patch
and published document into a draft state.
Has anyone worked through something similar?
Dec 14, 2023, 4:46 PM
A draft and a published document are actually two separate documents in your dataset. To unpublish something via the API, you need to create a draft version, which is done by creating a copy of the published document with the
_id
prefixed with
drafts.
) then delete the published document.
Dec 14, 2023, 6:50 PM
Perfect! It was a misunderstanding I had of what createIfNotExists does. Thanks!
Dec 14, 2023, 6:56 PM
You’re welcome!
Dec 14, 2023, 6:58 PM
I wonder if the documentation could have some more clarification around it? If I am understanding it correctly, something like this could be helpful:

Note: If you are wanting to change the state of a Published document to be "draft" then use the
createIfNotExists
function and set the id like so: `id: `drafts.previousDocId`` . This will create a draft document and leave a published Document. When published from the studio, the draft doc will merge with the published document and resolve changes
Dec 14, 2023, 7:09 PM
Yes! Something like that would be helpful. I’ll pass this along to the docs team. Thank you!
Dec 14, 2023, 7:10 PM
Here is an example function I have written that would do that if it can also be helpful

 import { merge } from 'lodash/fp' // not necessary just what I was using

const {
    docId,
    ...additionalProperties
  } = formData

const updateObject = {
    ...propertiesToUpdate
  }

const [published, draft] = await client.getDocuments([
    docId,
    `drafts.${docId}`,
  ])

  if (draft) {
    const res = await client.patch(docId).set(updateObject).commit()
  } else {
    const draftDoc = merge(
      { ...published, _id: `drafts.${docId}`, _type: 'card' },
      updateObject,
    )
    const res = await client.createIfNotExists(draftDoc)
  }
Dec 14, 2023, 7:16 PM
Also, shoutout to
user P
for the help and thoughts last week. Finally got it working!
Dec 14, 2023, 7:16 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?