Skip to content

Commit 64e982d

Browse files
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 <[email protected]> Co-authored-by: Simon Prickett <[email protected]> Closes #2280.
1 parent 1eed12e commit 64e982d

File tree

2 files changed

+59
-19
lines changed

2 files changed

+59
-19
lines changed

examples/README.md

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
This folder contains example scripts showing how to use Node Redis in different scenarios.
44

55
| File Name | Description |
6-
|-----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
6+
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
77
| `blocking-list-pop.js` | Block until an element is pushed to a list |
88
| `bloom-filter.js` | Space efficient set membership checks with a [Bloom Filter](https://en.wikipedia.org/wiki/Bloom_filter) using [RedisBloom](https://redisbloom.io) |
99
| `command-with-modifiers.js` | Define a script that allows to run a command with several modifiers |
@@ -12,7 +12,7 @@ This folder contains example scripts showing how to use Node Redis in different
1212
| `count-min-sketch.js` | Estimate the frequency of a given event using the [RedisBloom](https://redisbloom.io) Count-Min Sketch |
1313
| `cuckoo-filter.js` | Space efficient set membership checks with a [Cuckoo Filter](https://en.wikipedia.org/wiki/Cuckoo_filter) using [RedisBloom](https://redisbloom.io) |
1414
| `get-server-time.js` | Get the time from the Redis server |
15-
| `hyperloglog.js` | Showing use of Hyperloglog commands [PFADD, PFCOUNT and PFMERGE](https://redis.io/commands/?group=hyperloglog) |
15+
| `hyperloglog.js` | Showing use of Hyperloglog commands [PFADD, PFCOUNT and PFMERGE](https://redis.io/commands/?group=hyperloglog) |
1616
| `lua-multi-incr.js` | Define a custom lua script that allows you to perform INCRBY on multiple keys |
1717
| `managing-json.js` | Store, retrieve and manipulate JSON data atomically with [RedisJSON](https://redisjson.io/) |
1818
| `pubsub-publisher.js` | Adds multiple messages on 2 different channels messages to Redis |
@@ -26,10 +26,11 @@ This folder contains example scripts showing how to use Node Redis in different
2626
| `time-series.js` | Create, populate and query timeseries data with [Redis Timeseries](https://redistimeseries.io) |
2727
| `topk.js` | Use the [RedisBloom](https://redisbloom.io) TopK to track the most frequently seen items. |
2828
| `stream-consumer-group.js` | Reads entties from a [Redis Stream](https://redis.io/topics/streams-intro) as part of a consumer group using the blocking `XREADGROUP` command |
29+
| `transaction-with-watch.js` | An Example of [Redis transaction](https://redis.io/docs/manual/transactions) with `WATCH` command on isolated connection with optimistic locking |
2930

3031
## Contributing
3132

32-
We'd love to see more examples here. If you have an idea that you'd like to see included here, submit a Pull Request and we'll be sure to review it! Don't forget to check out our [contributing guide](../CONTRIBUTING.md).
33+
We'd love to see more examples here. If you have an idea that you'd like to see included here, submit a Pull Request and we'll be sure to review it! Don't forget to check out our [contributing guide](../CONTRIBUTING.md).
3334

3435
## Setup
3536

@@ -47,21 +48,21 @@ $ npm install
4748

4849
When adding a new example, please follow these guidelines:
4950

50-
* Add your code in a single JavaScript or TypeScript file per example, directly in the `examples` folder
51-
* Do not introduce other dependencies in your example
52-
* Give your `.js` file a meaningful name using `-` separators e.g. `adding-to-a-stream.js` / `adding-to-a-stream.ts`
53-
* Indent your code using 2 spaces
54-
* Use the single line `//` comment style and comment your code
55-
* Add a comment at the top of your `.js` / `.ts` file describing what your example does
56-
* Add a comment at the top of your `.js` / `.ts` file describing any Redis commands that need to be run to set up data for your example (try and keep this minimal)
57-
* Use semicolons
58-
* Use `async` and `await`
59-
* Use single quotes, `'hello'` not `"hello"`
60-
* Use [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) when embedding expressions in strings
61-
* Unless your example requires a connection string, assume Redis is on the default localhost port 6379 with no password
62-
* Use meaningful example data, let's not use `foo`, `bar`, `baz` etc!
63-
* Leave an empty line at the end of your `.js` file
64-
* Update this `README.md` file to add your example to the table
51+
- Add your code in a single JavaScript or TypeScript file per example, directly in the `examples` folder
52+
- Do not introduce other dependencies in your example
53+
- Give your `.js` file a meaningful name using `-` separators e.g. `adding-to-a-stream.js` / `adding-to-a-stream.ts`
54+
- Indent your code using 2 spaces
55+
- Use the single line `//` comment style and comment your code
56+
- Add a comment at the top of your `.js` / `.ts` file describing what your example does
57+
- Add a comment at the top of your `.js` / `.ts` file describing any Redis commands that need to be run to set up data for your example (try and keep this minimal)
58+
- Use semicolons
59+
- Use `async` and `await`
60+
- Use single quotes, `'hello'` not `"hello"`
61+
- Use [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) when embedding expressions in strings
62+
- Unless your example requires a connection string, assume Redis is on the default localhost port 6379 with no password
63+
- Use meaningful example data, let's not use `foo`, `bar`, `baz` etc!
64+
- Leave an empty line at the end of your `.js` file
65+
- Update this `README.md` file to add your example to the table
6566

6667
Use [connect-as-acl-user.js](./connect-as-acl-user.js) as a guide to develop a well formatted example script.
6768

@@ -87,5 +88,4 @@ await client.connect();
8788
// Add your example code here...
8889

8990
await client.quit();
90-
9191
```

examples/transaction-with-watch.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { createClient, WatchError } from 'redis';
2+
3+
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4+
const client = createClient();
5+
await client.connect();
6+
7+
function restrictFunctionCalls(fn, maxCalls) {
8+
let count = 1;
9+
return function (...args) {
10+
return count++ < maxCalls ? fn(...args) : false;
11+
};
12+
}
13+
14+
const fn = restrictFunctionCalls(transaction, 4);
15+
16+
async function transaction() {
17+
try {
18+
await client.executeIsolated(async (isolatedClient) => {
19+
await isolatedClient.watch('paymentId:1259');
20+
const multi = isolatedClient
21+
.multi()
22+
.set('paymentId:1259', 'Payment Successfully Completed!')
23+
.set('paymentId:1260', 'Refund Processed Successfully!');
24+
await delay(5000); // Do some changes to the watched key during this time...
25+
await multi.exec();
26+
console.log('Transaction completed Successfully!');
27+
client.quit();
28+
});
29+
} catch (error) {
30+
if (error instanceof WatchError) {
31+
console.log('Transaction Failed Due To Concurrent Modification!');
32+
fn();
33+
} else {
34+
console.log(`Error: ${error}`);
35+
client.quit();
36+
}
37+
}
38+
}
39+
40+
transaction();

0 commit comments

Comments
 (0)