Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Adds transaction with watched key example script. (#2297)
* transction example improved * readme fixed * delay added for watched key changes * pooling error fixed on recursion * Minor comment update. Co-authored-by: Ajay <ajay.markana@yudiz.com> Co-authored-by: Simon Prickett <simon@redis.com> Closes #2280.
- Loading branch information
1 parent
1eed12e
commit 64e982d
Showing
2 changed files
with
59 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { createClient, WatchError } from 'redis'; | ||
|
||
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); | ||
const client = createClient(); | ||
await client.connect(); | ||
|
||
function restrictFunctionCalls(fn, maxCalls) { | ||
let count = 1; | ||
return function (...args) { | ||
return count++ < maxCalls ? fn(...args) : false; | ||
}; | ||
} | ||
|
||
const fn = restrictFunctionCalls(transaction, 4); | ||
|
||
async function transaction() { | ||
try { | ||
await client.executeIsolated(async (isolatedClient) => { | ||
await isolatedClient.watch('paymentId:1259'); | ||
const multi = isolatedClient | ||
.multi() | ||
.set('paymentId:1259', 'Payment Successfully Completed!') | ||
.set('paymentId:1260', 'Refund Processed Successfully!'); | ||
await delay(5000); // Do some changes to the watched key during this time... | ||
await multi.exec(); | ||
console.log('Transaction completed Successfully!'); | ||
client.quit(); | ||
}); | ||
} catch (error) { | ||
if (error instanceof WatchError) { | ||
console.log('Transaction Failed Due To Concurrent Modification!'); | ||
fn(); | ||
} else { | ||
console.log(`Error: ${error}`); | ||
client.quit(); | ||
} | ||
} | ||
} | ||
|
||
transaction(); |