Skip to content

Commit

Permalink
[client] Allow specifying ID of transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Mar 3, 2018
1 parent e4801da commit 4e73a08
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
6 changes: 5 additions & 1 deletion packages/@sanity/client/src/data/dataMethods.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,11 @@ module.exports = {
: mutations
const muts = Array.isArray(mut) ? mut : [mut]

return this.dataRequest('mutate', {mutations: muts}, options)
return this.dataRequest(
'mutate',
{mutations: muts, transactionId: options && options.transactionId},
options
)
},

transaction(operations) {
Expand Down
22 changes: 16 additions & 6 deletions packages/@sanity/client/src/data/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@ const Patch = require('./patch')

const defaultMutateOptions = {returnDocuments: false}

function Transaction(operations = [], client) {
function Transaction(operations = [], client, transactionId) {
this.trxId = transactionId
this.operations = operations
this.client = client
}

assign(Transaction.prototype, {
clone() {
return new Transaction(
this.operations.slice(0),
this.client
)
return new Transaction(this.operations.slice(0), this.client, this.trxId)
},

create(doc) {
Expand Down Expand Up @@ -63,6 +61,15 @@ assign(Transaction.prototype, {
return this._add({patch: assign({id: documentId}, patchOps)})
},

transactionId(id) {
if (!id) {
return this.trxId
}

this.trxId = id
return this
},

serialize() {
return this.operations.slice()
},
Expand All @@ -79,7 +86,10 @@ assign(Transaction.prototype, {
)
}

return this.client.mutate(this.serialize(), assign({}, defaultMutateOptions, options || {}))
return this.client.mutate(
this.serialize(),
assign({transactionId: this.trxId}, defaultMutateOptions, options || {})
)
},

reset() {
Expand Down
20 changes: 20 additions & 0 deletions packages/@sanity/client/test/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1076,6 +1076,26 @@ test('transaction commit() throws if called without a client', t => {
t.end()
})

test('transaction can be given an explicit transaction ID', t => {
const transactionId = 'moop'
const mutations = [{create: {bar: true}}, {delete: {id: 'barfoo'}}]
nock(projectHost())
.post('/v1/data/mutate/foo?returnIds=true&visibility=sync', {mutations, transactionId})
.reply(200, {transactionId})

getClient().transaction()
.create({bar: true})
.delete('barfoo')
.transactionId(transactionId)
.commit()
.then(res => {
t.equal(res.transactionId, transactionId, 'applies given transaction')
})
.catch(t.ifError)
.then(t.end)
})


/*****************
* LISTENERS *
*****************/
Expand Down

0 comments on commit 4e73a08

Please sign in to comment.