Skip to content

Commit

Permalink
fix(api-request): using ecomClient for better parsing and queue control
Browse files Browse the repository at this point in the history
  • Loading branch information
leomp12 committed Mar 18, 2020
1 parent f556d97 commit fa3d2f2
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions lib/methods/api-request.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
'use strict'

const ecomClient = require('@ecomplus/client')

const apiRequest = client => {
const { collRef, db, table, axios } = client
const { collRef, db, table } = client
// handle new credentials
const getAuth = require('./get-auth')(client)

Expand All @@ -15,26 +17,24 @@ const apiRequest = client => {
// set authentication keys
const { myId, accessToken } = auth
let authenticated
// https://github.com/axios/axios#request-config
// https://developers.e-com.plus/client/ecomClient.html#.store
const options = {
storeId,
url,
method,
data,
headers: {
'X-Store-ID': storeId
}
data
}
if (myId && accessToken) {
authenticated = true
// authenticated request to Store API
options.headers['X-My-ID'] = myId
options.headers['X-Access-Token'] = accessToken
options.authenticationId = myId
options.accessToken = accessToken
}

// send HTTP request
let retry = 0
const req = () => {
axios(options).then(response => {
const send = () => {
ecomClient.store(options).then(response => {
// return response and used auth
resolve({ response, auth })
})
Expand Down Expand Up @@ -77,7 +77,7 @@ const apiRequest = client => {
if (status === 503 && retry < 2) {
// NGINX is blocking requests for security reasons
// wait few seconds and try again
setTimeout(req, 2000)
setTimeout(send, Math.floor(Math.random() * (6000 - 2000)) + 2000)
retry++
return
}
Expand All @@ -89,7 +89,8 @@ const apiRequest = client => {
error.appErrorLog = true

// try to log error on app hidden data
axios({
ecomClient.store({
...options,
url: '/applications/' + auth.row.application_id + '/hidden_data.json',
method: 'PATCH',
data: {
Expand All @@ -98,9 +99,7 @@ const apiRequest = client => {
method: config.method,
response: data
}
},
// keep used request headers
headers: options.headers
}
}).then(() => {
error.appErrorLogged = true
}).catch(err => {
Expand All @@ -120,7 +119,7 @@ const apiRequest = client => {

if (!authenticated) {
// no delay for public request
req()
send()
} else {
// control requests with delay
let delayFactor = running[storeId]
Expand All @@ -130,7 +129,7 @@ const apiRequest = client => {
running[storeId]++
setTimeout(() => {
running[storeId]--
req()
send()
}, delayFactor * 200)
}
}
Expand Down

0 comments on commit fa3d2f2

Please sign in to comment.