diff --git a/lib/datastores/24HoursRecordTable.js b/lib/datastores/24HoursRecordTable.js new file mode 100644 index 0000000..26b6004 --- /dev/null +++ b/lib/datastores/24HoursRecordTable.js @@ -0,0 +1,46 @@ +var debug = require('debug')('ylt:24HoursRecordTable'); + + +// Saves visits history and tells when limits are overpassed +function RecordTable(maxPerDay) { + var table = {}; + + // Check if the user overpassed the limit and save its visit + this.accepts = function(key) { + if (table[key]) { + + this.cleanEntry(key); + + debug('%d hits in the last 24 hours', table[key].length); + + if (table[key].length >= maxPerDay) { + return false; + } else { + table[key].push(Date.now()); + } + + } else { + table[key] = []; + table[key].push(Date.now()); + } + + return true; + }; + + // Clean the table for this guy + this.cleanEntry = function(key) { + table[key] = table[key].filter(function(date) { + return date > Date.now() - 1000*60*60*24; + }); + }; + + // Clean the entire table once in a while + this.removeOld = function() { + for (var key in table) { + this.cleanEntry(key); + } + }; + +} + +module.exports = RecordTable; \ No newline at end of file diff --git a/lib/middlewares/apiLimitsMiddleware.js b/lib/middlewares/apiLimitsMiddleware.js index 802c651..fb335ed 100644 --- a/lib/middlewares/apiLimitsMiddleware.js +++ b/lib/middlewares/apiLimitsMiddleware.js @@ -1,6 +1,8 @@ var config = (process.env.IS_TEST) ? require('../../test/fixtures/settings.json') : require('../../server_config/settings.json'); -var debug = require('debug')('apiLimitsMiddleware'); +var RecordTable = require('../datastores/24HoursRecordTable'); + +var debug = require('debug')('ylt:apiLimitsMiddleware'); var apiLimitsMiddleware = function(req, res, next) { @@ -46,48 +48,6 @@ var apiLimitsMiddleware = function(req, res, next) { next(); }; - -var RecordTable = function(maxPerDay) { - var table = {}; - - // Check if the user overpassed the limit and save its visit - this.accepts = function(ipAddress) { - if (table[ipAddress]) { - - this.cleanEntry(ipAddress); - - debug('%d visits in the last 24 hours', table[ipAddress].length); - - if (table[ipAddress].length >= maxPerDay) { - return false; - } else { - table[ipAddress].push(Date.now()); - } - - } else { - table[ipAddress] = []; - table[ipAddress].push(Date.now()); - } - - return true; - }; - - // Clean the table for this guy - this.cleanEntry = function(ipAddress) { - table[ipAddress] = table[ipAddress].filter(function(date) { - return date > Date.now() - 1000*60*60*24; - }); - }; - - // Clean the entire table once in a while - this.removeOld = function() { - for (var ipAddress in table) { - this.cleanEntry(ipAddress); - } - }; - -}; - // Init the records tables var runsTable = new RecordTable(config.maxAnonymousRunsPerDay); var callsTable = new RecordTable(config.maxAnonymousCallsPerDay);