Added cancellation by timeout

This commit is contained in:
Douglas Barone 2021-11-08 08:33:54 -04:00
parent ea0f9083c1
commit d7c4d4be15

View File

@ -1,8 +1,11 @@
import { create } from 'axios'
import { create, CancelToken } from 'axios'
import https from 'https'
import { ouiFinder } from '../utils/ouiFinder'
import { logError } from './logger'
const TIMEOUT_IN_MS = 120000
const REQUEST_TIMEOUT_IN_MS = 20000
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
ciphers: 'AES256-SHA' // That's necessary to connect to a TLS 1.0 server. Run node with --tls-min-v1.0
@ -10,16 +13,25 @@ const httpsAgent = new https.Agent({
const axios = create({
httpsAgent: httpsAgent,
timeout: REQUEST_TIMEOUT_IN_MS,
auth: {
username: process.env.CISCO_USER,
password: process.env.CISCO_PASSWORD
}
})
const getUri = (skip, page, take) =>
const getUrl = (skip, page, take) =>
`https://${process.env.CISCO_HOST}/data/client-table.html?columns=524287&take=${take}&skip=${skip}&page=${page}&pageSize=50&sort[0][field]=ST&sort[0][dir]=desc`
async function getDevices() {
function getDevices() {
return new Promise(async (resolve, reject) => {
const source = CancelToken.source()
const timeout = setTimeout(() => {
source.cancel('timeout')
reject(new Error('A operação getDevices foi cancelada pelo tempo limite'))
}, TIMEOUT_IN_MS)
let skip = 0
let page = 1
const take = 50
@ -27,38 +39,45 @@ async function getDevices() {
const responsesPromises = []
try {
let devices = []
let url = getUri(skip, page, take)
const firstResponse = await axios.get(url)
const firstResponse = await axios.get(getUrl(skip, page, take), {
cancelToken: source.token
})
const { total, data: page1devices } = firstResponse.data
devices = devices.concat(page1devices)
let devices = page1devices
skip += take
while (total > skip) {
responsesPromises.push(
axios.get(getUrl(skip, page, take), {
cancelToken: source.token
})
)
do {
skip += take
page++
let uri = getUri(skip, page, take)
responsesPromises.push(axios.get(uri))
} while (total > skip)
}
const responses = await Promise.all(responsesPromises)
clearTimeout(timeout)
responses.forEach(
({ data: { data: pageDevices } }) =>
(devices = devices.concat(pageDevices))
)
return devices
resolve(devices)
} catch (e) {
logError({
tags: ['cisco', 'wifiDevices'],
message: e.message,
data: { ...e, config: { ...e.config, auth: '*****' } }
})
return []
reject(e)
}
})
}
export async function getOnlineWifiDevices() {