Skip to content

Commit

Permalink
feat(core): add new documentIdEquals utility method
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Dec 16, 2022
1 parent 5e51831 commit f7eb4b3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/sanity/src/core/util/draftUtils.test.ts
@@ -1,5 +1,5 @@
import {SanityDocument} from '@sanity/types'
import {collate, removeDupes} from './draftUtils'
import {collate, documentIdEquals, removeDupes} from './draftUtils'

test('collate()', () => {
const foo = {_type: 'foo', _id: 'foo'}
Expand All @@ -22,3 +22,17 @@ test('removeDupes()', () => {

expect(removeDupes([foo, fooDraft, barDraft, baz])).toEqual([fooDraft, barDraft, baz])
})

test.each([
['full equality, published', 'agot', 'agot', true],
['full equality, drafts', 'drafts.agot', 'drafts.agot', true],
['lhs draft, rhs published', 'drafts.agot', 'agot', true],
['rhs draft, lhs published', 'agot', 'drafts.agot', true],
['differing documents', 'agot', 'adwd', false],
['differing documents, draft lhs', 'drafts.agot', 'adwd', false],
['differing documents, draft rhs', 'agot', 'drafts.adwd', false],
['lhs non-draft prefix, otherwise equality', 'notes.agot', 'agot', false],
['rhs non-draft prefix, otherwise equality', 'agot', 'notes.agot', false],
])('documentIdEquals(): %s', (_, documentId, equalsDocumentId, shouldEqual) => {
expect(documentIdEquals(documentId, equalsDocumentId)).toEqual(shouldEqual)
})
23 changes: 23 additions & 0 deletions packages/sanity/src/core/util/draftUtils.ts
Expand Up @@ -15,6 +15,29 @@ export type PublishedId = Opaque<string, 'publishedId'>
export const DRAFTS_FOLDER = 'drafts'
const DRAFTS_PREFIX = `${DRAFTS_FOLDER}.`

/**
* Checks if the document ID `documentId` has the same ID as `equalsDocumentId`,
* if you discard the draft status of the given IDs. Examples:
*
* @example
* Draft vs published document ID, but representing the same document:
* ```
* // Prints "true":
* console.log(documentIdEquals('drafts.agot', 'agot'));
* ```
* @example
* Different documents:
* ```
* // Prints "false":
* console.log(documentIdEquals('hp-tcos', 'hp-hbp'));
* ```
*
* @public
*/
export function documentIdEquals(documentId: string, equalsDocumentId: string): boolean {
return getPublishedId(documentId) === getPublishedId(equalsDocumentId)
}

/** @internal */
export function isDraft(document: SanityDocument): boolean {
return isDraftId(document._id)
Expand Down

1 comment on commit f7eb4b3

@vercel
Copy link

@vercel vercel bot commented on f7eb4b3 Dec 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

test-studio – ./

test-studio.sanity.build
test-studio-git-next.sanity.build

Please sign in to comment.