-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(method): new 'requestStoreApi' method
- Loading branch information
Showing
2 changed files
with
74 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |