Reputation: 135
I have an application that has connects to Redis, Mongo, and Elasticsearch but how can I make sure all the connections are connected before the app is served? I notice that Elasticsearch usually takes longer and when I test my app using Supertest that the database connects but the console.info('Successfully connected to db');
doesn't log to the console before the tests start to run.
server.ts
const client = redis.createClient({ host: process.env.REDIS })
client.on('connect', function () {
console.log('Redis client connected');
});
mongoose
.connect(dbURL)
.then(() => {
return console.info(`Successfully connected to ${db}`);
})
.catch(error => {
console.error('Error connecting to database: ', error);
return process.exit(1);
});
};
const app = express();
export default app;
main.ts
import server from './server'
server.listen(8000)
Upvotes: 0
Views: 49
Reputation: 1415
You should "promisify" all your connection processes, and then wait for all promises to be resolved before starting the app:
import server from './server'
const connectRedis = host => {
return new Promise(resolve => {
const client = redis.createClient({ host });
client.on("connect", () => {
console.log("Redis client connected");
resolve(client);
});
});
}
const connectMongo = dbURL => {
return mongoose.connect(dbURL)
};
const connectAll = ({ mongoDbURL, redisHost }) => {
return Promise.all([
connectRedis(redisHost),
connectMongo(mongoDbURL)
]);
}
connectAll({
mongoDbUrl: process.env.MONGODB_URL,
redisHost: process.env.REDIS,
}).then(() => {
server.listen(8000)
});
Upvotes: 1
Reputation: 7267
You can export a connection Promise for each of the connection
and then in the main app, do this
Promise.all([
connectRedisPromise(),
connectMongoPromise(),
connectESPromise(),
]).then(() => {
// start the app
})
Upvotes: 1