Skip to content

Commit

Permalink
Adds failover to database connection #179
Browse files Browse the repository at this point in the history
  • Loading branch information
ManjotS committed Jun 22, 2020
1 parent c50a0e4 commit c6d05c9
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 31 deletions.
15 changes: 10 additions & 5 deletions api/config/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,33 @@ const metadata = {
password: process.env.DB_PASSWORD || 'root',
database: process.env.NODE_ENV === 'development' ? 'khajana_dev_khajana' : 'khajana_khajana',
dateStrings: true,
acquireTimeout: 5000,
connectionLimit: process.env.DB_POOL_SIZE,
};
const standbyMetadata = {
port: 3306,
minimumIdle: 0,
};

module.exports = {
mysql0: {
host: 'localhost',
port: process.env.DB_PORT || 3306,
...metadata,
},
mysql2: {
mysql1: {
host: 'db1.khalis.net',
port: 3306,
...metadata,
...standbyMetadata,
},
mysql2: {
host: 'db2.khalis.net',
port: 3306,
...metadata,
...standbyMetadata,
},
mysql2: {
mysql3: {
host: 'db3.khalis.net',
port: 3306,
...metadata,
...standbyMetadata,
},
};
32 changes: 6 additions & 26 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,19 @@ const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const cacheControl = require('express-cache-controller');
const { createPool } = require('mariadb');
const { createPoolCluster } = require('mariadb');
const config = require('./api/config');
const routes = require('./api/routes');

const app = express();
const port = process.env.NODE_ENV === 'development' ? '3001' : '3000';

//database
try {
app.locals.pool = createPool(config.mysql0);
app.local.pool.getConnection().query('SELECT 1');
} catch (err) {
try {
app.locals.pool = createPool(config.mysql1);
app.local.pool.getConnection().query('SELECT 1');
console.log('Failed to DB1');
} catch (err) {
try {
app.locals.pool = createPool(config.mysql2);
app.local.pool.getConnection().query('SELECT 1');
console.log('Failed to DB2');
} catch (err) {
try {
app.locals.pool = createPool(config.mysql3);
app.local.pool.getConnection().query('SELECT 1');
console.log('Failed to DB3');
} catch (err) {
console.log('Could not connect to any database!');
console.log(err);
}
}
}
}
app.locals.pool = createPoolCluster();
app.locals.pool.add('local', config.mysql0);
app.locals.pool.add('db1', config.mysql1);
app.locals.pool.add('db2', config.mysql2);
app.locals.pool.add('db3', config.mysql3);

// app
app.use(cors());
Expand Down

0 comments on commit c6d05c9

Please sign in to comment.