From e99cb819accadbf3bf25c946ea3f8b052b519074 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20F=2E=20Romaniello?= Date: Wed, 30 Aug 2017 17:21:18 -0300 Subject: [PATCH] add bucket hierarchy --- lib/db.js | 14 +++++++++++++- test/db.tests.js | 12 ++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/db.js b/lib/db.js index 116efb1..3f8ca20 100644 --- a/lib/db.js +++ b/lib/db.js @@ -24,7 +24,8 @@ function normalizeType(params) { 'per_interval', 'interval', 'size', - 'unlimited' + 'unlimited', + 'depends_on' ]); INTERVAL_SHORTCUTS.forEach(ish => { @@ -202,6 +203,17 @@ class LimitDB { return bucket; }, { ttl: typeParams.ttl }, (err, bucket) => { if (err) { return callback(err); } + if (bucket.lastConformant && typeParams.depends_on) { + return this.take(_.extend({}, params, { type: typeParams.depends_on }), (err, dep) => { + if (err) { return callback(err); } + callback(null, { + conformant: dep.conformant, + remaining: Math.min(bucket.remaining, dep.remaining), + reset: Math.min(bucket.reset, dep.reset), + limit: Math.min(bucket.limit, dep.limit), + }); + }); + } callback(null, { conformant: bucket.lastConformant, remaining: Math.floor(bucket.content), diff --git a/test/db.tests.js b/test/db.tests.js index 7063c1b..369053b 100644 --- a/test/db.tests.js +++ b/test/db.tests.js @@ -33,6 +33,10 @@ const types = { size: 10 } } + }, + 'ip child': { + depends_on: 'ip', + per_second: 100 } }; @@ -259,6 +263,14 @@ describe('LimitDB', () => { }); }); + it('should work with depends_on', (done) => { + db.take({ type: 'ip child', key: '1.1.1.1', count: 20 }, (err, response) => { + if (err) { return done(err); } + assert.notOk(response.conformant); + done(); + }); + }); + }); describe('PUT', function () {