diff --git a/package.json b/package.json index 63a7beb0..ab7bebb8 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "fetch-ponyfill": "^4.1.0", "lodash": "^4.17.4", "luxon": "^0.3.1", + "p-throttle": "^1.1.0", "pinkie-promise": "^2.0.1", "query-string": "^5.0.0", "slugg": "^1.2.0", diff --git a/test/index.js b/test/index.js index 5675edb4..b278e8d2 100644 --- a/test/index.js +++ b/test/index.js @@ -3,3 +3,4 @@ require('./db') require('./vbb') require('./oebb') +require('./throttle') diff --git a/test/throttle.js b/test/throttle.js new file mode 100644 index 00000000..cc849218 --- /dev/null +++ b/test/throttle.js @@ -0,0 +1,27 @@ +'use strict' + +const test = require('tape') + +const createThrottledClient = require('../throttle') +const vbbProfile = require('../p/vbb') + +const spichernstr = '900000042101' + +test('throttle works', (t) => { + let calls = 0 + const transformReqBody = (body) => { + calls++ + return vbbProfile.transformReqBody(body) + } + const mockProfile = Object.assign({}, vbbProfile, {transformReqBody}) + + const client = createThrottledClient(mockProfile, 2, 1000) + for (let i = 0; i < 10; i++) client.departures(spichernstr, {duration: 1}) + + t.plan(3) + setTimeout(() => t.equal(calls, 2), 500) + setTimeout(() => t.equal(calls, 4), 1500) + setTimeout(() => t.equal(calls, 6), 2500) +}) + +// todo diff --git a/throttle.js b/throttle.js new file mode 100644 index 00000000..99fb3cc0 --- /dev/null +++ b/throttle.js @@ -0,0 +1,13 @@ +'use strict' + +const throttle = require('p-throttle') + +const request = require('./lib/request') +const createClient = require('.') + +const createThrottledClient = (profile, limit = 5, interval = 1000) => { + const throttledRequest = throttle(request, limit, interval) + return createClient(profile, throttledRequest) +} + +module.exports = createThrottledClient