Skip to content
Snippets Groups Projects
Commit ab11e23b authored by Lucendio's avatar Lucendio
Browse files

[app/server] service does not require db connection anymore to come up properly

* change behaviour so that service still comes up regardless whether db connection
  can be established or not (see 12-Factor-App) - loosely tight to backing service
* instead, it will log to stderr hinting this issue
* successful port binding is still required
parent c1e57f76
No related branches found
No related tags found
No related merge requests found
const mongoose = require('mongoose');
const mongooseInstance_ = mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
const mongooseInstance_ = mongoose.connect(
process.env.MONGODB_URL,
{
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
// NOTE: as of the docs `connectTimeoutMS` should be used when `useUnifiedTopology: true`,
// but apparently it has no impact what so ever. Instead, the following works ¯\_(ツ)_/¯
serverSelectionTimeoutMS: 7000 // 7 sec
// NOTE: as of the docs `connectTimeoutMS` should be used when `useUnifiedTopology: true`,
// but apparently it has no impact what so ever. Instead, the following works ¯\_(ツ)_/¯
serverSelectionTimeoutMS: 10000 // 10 sec
},
function( err ){
if( typeof err !== 'undefined' && err !== null ){
console.error( new Error( `Cannot connect to database: ${ process.env.MONGODB_URL }` ) );
}else{
console.log( `Connect established to database: ${ process.env.MONGODB_URL }` );
}
}
);
process.on( 'exit', async ()=>{
const dbClient = await mongooseInstance_;
dbClient.disconnect();
});
......
......@@ -39,19 +39,14 @@ app.use(errorRoutes);
(async function main(){
try{
const dbClient = await dbClientInstance_;
process.on( 'exit', ()=>{
dbClient.disconnect();
});
await new Promise( (__ful, rej__ )=>{
app.listen(port, function(){
console.log( `ToDo server is up on port ${ port }`);
__ful();
}).on( 'error', rej__);
});
}catch(e){
console.error( new Error( `Cannot connect to database ${ process.env.MONGODB_URL }` ) );
}catch( err ){
console.error( err );
process.exit( 1 );
}
})();
......@@ -5,16 +5,15 @@ const { model: Users } = require( './Users.js' );
describe( 'Model: Users', ()=>{
beforeAll( async ()=>{
await dbClientInstance_;
try{
await dbClientInstance_;
}catch( err ){
console.error( new Error( `Cannot connect to database: ${ process.env.MONGODB_URL }` ) );
process.exit( 1 );
}
});
const userData = {
name: 'myname',
email: 'myname@example.com',
password: 'mypassword'
};
test( 'creating a user', async ()=>{
const userData = {
name: 'myname',
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment