request throttling

This commit is contained in:
Jannis R 2018-01-23 15:54:39 +01:00
parent c3c3c08e7d
commit 04fb329a7e
No known key found for this signature in database
GPG key ID: 0FE83946296A88A5
4 changed files with 42 additions and 0 deletions

View file

@ -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",

View file

@ -3,3 +3,4 @@
require('./db')
require('./vbb')
require('./oebb')
require('./throttle')

27
test/throttle.js Normal file
View file

@ -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

13
throttle.js Normal file
View file

@ -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