Work on refactoring global IP ban database calls

This commit is contained in:
Calvin Montgomery 2017-05-31 22:46:06 -07:00
parent 7fcf31dec6
commit d0712d007e
5 changed files with 192 additions and 20 deletions

View file

@ -14,29 +14,40 @@ var global_ipbans = {};
let db = null;
class Database {
constructor() {
const config = {
client: 'mysql',
connection: {
host: Config.get('mysql.server'),
port: Config.get('mysql.port'),
user: Config.get('mysql.user'),
password: Config.get('mysql.password'),
database: Config.get('mysql.database'),
multipleStatements: true, // Legacy thing
charset: 'UTF8MB4_GENERAL_CI'
},
pool: {
min: Config.get('mysql.pool-size'),
max: Config.get('mysql.pool-size')
},
debug: !!process.env.KNEX_DEBUG
};
constructor(knexConfig = null) {
if (knexConfig === null) {
knexConfig = {
client: 'mysql',
connection: {
host: Config.get('mysql.server'),
port: Config.get('mysql.port'),
user: Config.get('mysql.user'),
password: Config.get('mysql.password'),
database: Config.get('mysql.database'),
multipleStatements: true, // Legacy thing
charset: 'UTF8MB4_GENERAL_CI'
},
pool: {
min: Config.get('mysql.pool-size'),
max: Config.get('mysql.pool-size')
},
debug: !!process.env.KNEX_DEBUG
};
}
this.knex = knex(config);
this.knex = knex(knexConfig);
}
runTransaction(fn) {
const timer = Metrics.startTimer('db:queryTime');
return this.knex.transaction(fn).finally(() => {
Metrics.stopTimer(timer);
});
}
}
module.exports.Database = Database;
module.exports.init = function () {
db = new Database();
db.knex.raw('select 1 from dual')

52
src/db/globalban.js Normal file
View file

@ -0,0 +1,52 @@
import { LoggerFactory } from '@calzoneman/jsli';
import util from '../utilities';
import Promise from 'bluebird';
const LOGGER = LoggerFactory.getLogger('GlobalBanDB');
class GlobalBanDB {
constructor(db) {
this.db = db;
}
listGlobalBans() {
return this.db.runTransaction(tx => {
return tx.table('global_bans').select();
}).catch(error => {
LOGGER.error('Failed to list global IP bans: %s', error.stack);
throw error;
});
}
addGlobalIPBan(ip, reason) {
return this.db.runTransaction(tx => {
return tx.table('global_bans')
.insert({ ip, reason })
.catch(error => {
if (error.code === 'ER_DUP_ENTRY') {
return tx.table('global_bans')
.where({ ip })
.update({ reason });
} else {
throw error;
}
});
}).catch(error => {
LOGGER.error('Failed to add global IP ban for IP %s: %s', ip, error.stack);
throw error;
});
}
removeGlobalIPBan(ip) {
return this.db.runTransaction(tx => {
return tx.table('global_bans')
.where({ ip })
.del();
}).catch(error => {
LOGGER.error('Failed to remove global IP ban for IP %s: %s', ip, error.stack);
throw error;
});
}
}
export { GlobalBanDB };