Skip to content

Commit

Permalink
update optional route syntax to /{:query} and refactor Redis initiali…
Browse files Browse the repository at this point in the history
…zation into dedicated function to guarantee that it is complete before server starts
  • Loading branch information
vinybk committed Jan 12, 2025
1 parent 4148e66 commit ff948b5
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions examples/search/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,37 +16,40 @@ var path = require('node:path');
var redis = require('redis');

var db = redis.createClient();
var app = express();

// npm install redis
app.use(express.static(path.join(__dirname, 'public')));

// connect to Redis
// npm install redis

db.connect()
.catch((err) => console.error('Redis connection error:', err));
/**
* Redis Initialization
*/

var app = express();
async function initializeRedis() {
try {
// connect to Redis

app.use(express.static(path.join(__dirname, 'public')));
await db.connect();

// populate search
// populate search

(async () => {
try {
await db.sAdd('ferret', 'tobi');
await db.sAdd('ferret', 'loki');
await db.sAdd('ferret', 'jane');
await db.sAdd('cat', 'manny');
await db.sAdd('cat', 'luna');
} catch (err) {
console.error('Error populating Redis:', err);
console.error('Error initializing Redis:', err);
process.exit(1);
}
})();
}

/**
* GET search for :query.
*/

app.get('/search/:query{0,1}', function (req, res, next) {
app.get('/search/{:query}', function (req, res, next) {
var query = req.params.query || '';
db.sMembers(query)
.then((vals) => res.send(vals))
Expand All @@ -67,8 +70,14 @@ app.get('/client.js', function(req, res){
res.sendFile(path.join(__dirname, 'client.js'));
});

/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
/**
* Start the Server
*/

(async () => {
await initializeRedis();
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
})();

0 comments on commit ff948b5

Please sign in to comment.