Skip to content

Commit

Permalink
feat(method): new 'requestStoreApi' method
Browse files Browse the repository at this point in the history
  • Loading branch information
leomp12 committed Jul 9, 2019
1 parent 46b6ef9 commit 6ef943b
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import _self from './lib/self'

import requestStoreApi from './methods/request-store-api'

/**
* JS client for E-Com Plus REST APIs.
* @module @ecomplus/client
Expand All @@ -25,7 +27,8 @@ import _self from './lib/self'
*/

export {
_self
_self,
requestStoreApi
}

/**
Expand Down
70 changes: 70 additions & 0 deletions src/methods/request-store-api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { _config } from '@ecomplus/utils'
import { API_STORE, API_STORE_CACHE } from './../lib/constants'
import axios from './../lib/axios'

// save Store Cache API status
let isCacheOnline = true

const requestStoreApi = (
url,
method = 'get',
data,
storeId = _config.get('store_id'),
authenticationId = _config.get('authentication_id'),
accessToken = _config.get('access_token'),
axiosConfig
) => {
let timeout, baseURL
const headers = {
'X-Store-ID': storeId
}

// first check if it's a public request
if (method.toLowerCase() === 'get' && !authenticationId) {
// less timeout for public requests
timeout = 5000
// use cache API host for public requests
baseURL = isCacheOnline ? API_STORE_CACHE : API_STORE
} else {
baseURL = API_STORE
// setup authentication headers
headers['X-My-ID'] = authenticationId
headers['X-Access-Token'] = accessToken
}

// returns axios request promise
return axios.request({
url,
baseURL,
method,
data,
headers,
timeout,
...axiosConfig
})

.catch(err => {
if (baseURL === API_STORE_CACHE) {
// retry with live Store API
let { status } = err.response
if (!status || status >= 500) {
isCacheOnline = false
setTimeout(() => { isCacheOnline = true }, 30000)
// resend request with same params
return requestStoreApi(
url,
method,
data,
storeId,
authenticationId,
accessToken,
axiosConfig
)
}
}
// chain promise catch
throw err
})
}

export default requestStoreApi

0 comments on commit 6ef943b

Please sign in to comment.