Skip to content

Commit e6b1d93

Browse files
committed
update optional route syntax to /{:query} and refactor Redis initialization into dedicated function to guarantee that it is complete before server starts
1 parent 4148e66 commit e6b1d93

File tree

1 file changed

+28
-18
lines changed

1 file changed

+28
-18
lines changed

examples/search/index.js

+28-18
Original file line numberDiff line numberDiff line change
@@ -16,37 +16,40 @@ var path = require('node:path');
1616
var redis = require('redis');
1717

1818
var db = redis.createClient();
19-
20-
// npm install redis
21-
22-
// connect to Redis
23-
24-
db.connect()
25-
.catch((err) => console.error('Redis connection error:', err));
26-
2719
var app = express();
2820

2921
app.use(express.static(path.join(__dirname, 'public')));
3022

31-
// populate search
23+
// npm install redis
3224

33-
(async () => {
25+
/**
26+
* Redis Initialization
27+
*/
28+
29+
async function initializeRedis() {
3430
try {
31+
// connect to Redis
32+
33+
await db.connect();
34+
35+
// populate search
36+
3537
await db.sAdd('ferret', 'tobi');
3638
await db.sAdd('ferret', 'loki');
3739
await db.sAdd('ferret', 'jane');
3840
await db.sAdd('cat', 'manny');
3941
await db.sAdd('cat', 'luna');
4042
} catch (err) {
41-
console.error('Error populating Redis:', err);
43+
console.error('Error initializing Redis:', err);
44+
process.exit(1);
4245
}
43-
})();
46+
}
4447

4548
/**
4649
* GET search for :query.
4750
*/
4851

49-
app.get('/search/:query{0,1}', function (req, res, next) {
52+
app.get('/search/{:query}', function (req, res, next) {
5053
var query = req.params.query || '';
5154
db.sMembers(query)
5255
.then((vals) => res.send(vals))
@@ -67,8 +70,15 @@ app.get('/client.js', function(req, res){
6770
res.sendFile(path.join(__dirname, 'client.js'));
6871
});
6972

70-
/* istanbul ignore next */
71-
if (!module.parent) {
72-
app.listen(3000);
73-
console.log('Express started on port 3000');
74-
}
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+
}
84+
})();

0 commit comments

Comments
 (0)