From c37f41042939546b4569beda772a34624411612e Mon Sep 17 00:00:00 2001 From: Sebastian Rindom Date: Sun, 23 Aug 2020 16:50:54 +0200 Subject: [PATCH] Add rate limiting --- .../medusa-plugin-brightpearl/package.json | 1 + .../src/utils/brightpearl.js | 22 +++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/medusa-plugin-brightpearl/package.json b/packages/medusa-plugin-brightpearl/package.json index 0c579d2a1f..20ecbe0c77 100644 --- a/packages/medusa-plugin-brightpearl/package.json +++ b/packages/medusa-plugin-brightpearl/package.json @@ -36,6 +36,7 @@ }, "dependencies": { "axios": "^0.19.2", + "axios-rate-limit": "^1.2.1", "express": "^4.17.1", "medusa-core-utils": "^1.0.0-alpha.3", "medusa-interfaces": "^1.0.0-alpha.3", diff --git a/packages/medusa-plugin-brightpearl/src/utils/brightpearl.js b/packages/medusa-plugin-brightpearl/src/utils/brightpearl.js index a7f72cb66b..b549430d9b 100644 --- a/packages/medusa-plugin-brightpearl/src/utils/brightpearl.js +++ b/packages/medusa-plugin-brightpearl/src/utils/brightpearl.js @@ -1,6 +1,11 @@ import axios from "axios" +import rateLimit from "axios-rate-limit" import qs from "querystring" +// Brightpearl allows 200 requests per minute +const RATE_LIMIT_REQUESTS = 200 +const RATE_LIMIT_INTERVAL = 60 * 1000 + class BrightpearlClient { static createToken(account, data) { const params = { @@ -40,13 +45,16 @@ class BrightpearlClient { } constructor(options, onRefreshToken) { - this.client_ = axios.create({ - baseURL: `https://${options.url}/public-api/${options.account}`, - headers: { - "brightpearl-app-ref": "medusa-dev", - "brightpearl-dev-ref": "sebrindom", - }, - }) + this.client_ = rateLimit( + axios.create({ + baseURL: `https://${options.url}/public-api/${options.account}`, + headers: { + "brightpearl-app-ref": "medusa-dev", + "brightpearl-dev-ref": "sebrindom", + }, + }), + { maxRequests: RATE_LIMIT_REQUESTS, perMilliseconds: RATE_LIMIT_INTERVAL } + ) this.authType_ = options.auth_type this.token_ = options.access_token