Skip to content

Commit d127723

Browse files
vinybkbjohansebas
andauthored
fix: search example to support Redis v4+ and Express 4/5 (#6274)
* Fix Redis example to support Redis v4+ and Express 4/5 * update optional route syntax to /{:query} and refactor Redis initialization into dedicated function to guarantee that it is complete before server starts --------- Co-authored-by: Sebastian Beltran <[email protected]>
1 parent 6b7ccfc commit d127723

File tree

1 file changed

+41
-19
lines changed

1 file changed

+41
-19
lines changed

examples/search/index.js

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,31 +16,47 @@ var path = require('node:path');
1616
var redis = require('redis');
1717

1818
var db = redis.createClient();
19+
var app = express();
20+
21+
app.use(express.static(path.join(__dirname, 'public')));
1922

2023
// npm install redis
2124

22-
var app = express();
25+
/**
26+
* Redis Initialization
27+
*/
2328

24-
app.use(express.static(path.join(__dirname, 'public')));
29+
async function initializeRedis() {
30+
try {
31+
// connect to Redis
2532

26-
// populate search
33+
await db.connect();
2734

28-
db.sadd('ferret', 'tobi');
29-
db.sadd('ferret', 'loki');
30-
db.sadd('ferret', 'jane');
31-
db.sadd('cat', 'manny');
32-
db.sadd('cat', 'luna');
35+
// populate search
36+
37+
await db.sAdd('ferret', 'tobi');
38+
await db.sAdd('ferret', 'loki');
39+
await db.sAdd('ferret', 'jane');
40+
await db.sAdd('cat', 'manny');
41+
await db.sAdd('cat', 'luna');
42+
} catch (err) {
43+
console.error('Error initializing Redis:', err);
44+
process.exit(1);
45+
}
46+
}
3347

3448
/**
3549
* GET search for :query.
3650
*/
3751

38-
app.get('/search/:query?', function(req, res, next){
39-
var query = req.params.query;
40-
db.smembers(query, function(err, vals){
41-
if (err) return next(err);
42-
res.send(vals);
43-
});
52+
app.get('/search/{:query}', function (req, res, next) {
53+
var query = req.params.query || '';
54+
db.sMembers(query)
55+
.then((vals) => res.send(vals))
56+
.catch((err) => {
57+
console.error(`Redis error for query "${query}":`, err);
58+
next(err);
59+
});
4460
});
4561

4662
/**
@@ -54,8 +70,14 @@ app.get('/client.js', function(req, res){
5470
res.sendFile(path.join(__dirname, 'client.js'));
5571
});
5672

57-
/* istanbul ignore next */
58-
if (!module.parent) {
59-
app.listen(3000);
60-
console.log('Express started on port 3000');
61-
}
73+
/**
74+
* Start the Server
75+
*/
76+
77+
(async () => {
78+
await initializeRedis();
79+
if (!module.parent) {
80+
app.listen(3000);
81+
console.log('Express started on port 3000');
82+
}
83+
})();

0 commit comments

Comments
 (0)