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 e6b1d93
Showing 1 changed file with 28 additions and 18 deletions.
46 changes: 28 additions & 18 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();

// npm install redis

// connect to Redis

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

var app = express();

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

// populate search
// npm install redis

(async () => {
/**
* Redis Initialization
*/

async function initializeRedis() {
try {
// connect to Redis

await db.connect();

// populate search

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,15 @@ 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 e6b1d93

Please sign in to comment.