Skip to content

Commit

Permalink
refactor(core): simplifiying guarantee on createdAt date; testing aro…
Browse files Browse the repository at this point in the history
…und missing timestamp
  • Loading branch information
jordanl17 committed Sep 15, 2024
1 parent 308a4b6 commit 4d06ccd
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
6 changes: 1 addition & 5 deletions packages/@sanity/mutator/src/document/Mutation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import {isString} from 'lodash'

import {Patcher} from '../patch'
import {debug} from './debug'
import {luid} from './luid'
Expand Down Expand Up @@ -110,9 +108,7 @@ export class Mutation {

// creation requires a _createdAt
const getGuaranteedCreatedAt = (doc: Doc): string =>
doc && isString(doc._createdAt)
? doc._createdAt
: this.params.timestamp || new Date().toISOString()
doc?._createdAt || this.params.timestamp || new Date().toISOString()

this.mutations.forEach((mutation) => {
if (mutation.create) {
Expand Down
29 changes: 29 additions & 0 deletions packages/@sanity/mutator/test/SquashingBuffer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,35 @@ test('de-duplicate createIfNotExists', () => {
expect(tx2 && tx2.mutations.length).toBe(1)
})

test.each(['create', 'createIfNotExists', 'createOrReplace'])(
'%s defaults to current created at time',
(createFnc) => {
const globalMockDate = new Date('2020-01-01T12:34:55.000Z')
const globalDateSpy = jest.spyOn(global, 'Date').mockReturnValue(globalMockDate)

const sb = new SquashingBuffer(null)

add(sb, {[createFnc]: {_id: '1', _type: 'test', a: 'A string value'}})

const tx = sb.purge('txn_id')
if (!tx) {
throw new Error('buffer purge did not result in a mutation')
}

const final = tx.apply(null)

expect(final).toEqual({
_id: '1',
_rev: 'txn_id',
_createdAt: '2020-01-01T12:34:55.000Z',
_type: 'test',
a: 'A string value',
})

globalDateSpy.mockRestore()
},
)

test('de-duplicate create respects deletes', () => {
const globalMockDate = new Date('2020-01-01T12:34:55.000Z')
const globalDateSpy = jest.spyOn(global, 'Date').mockReturnValue(globalMockDate)
Expand Down

0 comments on commit 4d06ccd

Please sign in to comment.