Skip to content

Commit

Permalink
feat(webapp): add timeout when endpoint is called
Browse files Browse the repository at this point in the history
  • Loading branch information
Torresmorah committed Dec 23, 2022
1 parent 495ea5a commit fde0d53
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions webapp/src/utils/eosapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const ENDPOINTS_ERROR =
'Each endpoint failed when trying to execute the function'

const waitRequestInterval = 300000
const timeout = 5000
const eosApis = eosConfig.endpoints.map(endpoint => {
return {
api: EosApi({
Expand All @@ -25,19 +26,15 @@ const callEosApi = async method => {
if (diffTime < waitRequestInterval) continue

try {
const response = await method(eosApi.api)
const response = await callWithTimeout(method(eosApi.api), timeout)
let headBlockTime = response.head_block_time

if (!headBlockTime) {
const info = await eosApi.api.getInfo({})
if (headBlockTime) {
const diffBlockTimems = new Date() - new Date(headBlockTime)

headBlockTime = info.head_block_time
}

const diffBlockTimems = new Date() - new Date(headBlockTime)

if (diffBlockTimems > eosConfig.syncToleranceInterval) {
throw new Error(`The endpoint ${eosApi.endpoint} is outdated`)
if (diffBlockTimems > eosConfig.syncToleranceInterval) {
throw new Error(`The endpoint ${eosApi.endpoint} is outdated`)
}
}

return response
Expand All @@ -57,6 +54,20 @@ const callEosApi = async method => {
throw new Error(ENDPOINTS_ERROR)
}

const callWithTimeout = async (promise, ms) => {
let timeoutID
const timeoutMessage = `timeout error: the endpoint took more than ${ms} ms to respond`
const timeoutPromise = new Promise((_resolve, reject) => {
timeoutID = setTimeout(() => reject(new Error(timeoutMessage)), ms)
})

return Promise.race([promise, timeoutPromise]).then((response) => {
clearTimeout(timeoutID)

return response
})
}

const getAbi = async account => {
return await callEosApi(async eosApi => eosApi.getAbi(account))
}
Expand Down

0 comments on commit fde0d53

Please sign in to comment.