axios#CancelToken TypeScript Examples
The following examples show how to use
axios#CancelToken.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: dns_handler.ts From SpaceEye with MIT License | 5 votes |
/**
* Resolve the IP of a request URL by sending a HEAD request to each A record,
* using the first IP to respond.
*
* @param requestUrl - URL being requested
* @param cancelToken - Cancel token to stop DNS probes
* @returns Resolved IP address
*/
export async function resolveDns(requestUrl: Url.URL, cancelToken?: CancelToken): Promise<string> {
const addressInfo = await asyncLookup(requestUrl.hostname, { all: true })
// Probably won't ever happen, but just in case
if (addressInfo.length === 0) {
log.error(
'Unable to resolve',
requestUrl.hostname,
'to an address. Unexpected behavior may ensue.'
)
}
const configStore = SatelliteConfigStore.Instance
if (
configStore.dnsProbeOverrideDomains !== undefined &&
configStore.dnsProbeOverrideDomains.includes(requestUrl.hostname)
) {
log.debug('Skipping DNS probing on', requestUrl.hostname)
return addressInfo[0].address
}
return new Promise((resolve, reject) => {
const probeCancelToken = Axios.CancelToken.source()
let complete = false
// Cancel DNS probes if overarching request was cancelled
if (cancelToken !== undefined) {
cancelToken.promise.then(() => {
complete = true
probeCancelToken.cancel()
})
}
const requests = addressInfo.map(info => {
const testingUrl = new URL(requestUrl.toString())
testingUrl.hostname = info.address
return Axios.head(testingUrl.toString(), {
headers: { Host: requestUrl.hostname },
cancelToken: probeCancelToken.token,
timeout: 5000
})
.then(() => {
complete = true
probeCancelToken.cancel()
log.debug('Resolved', requestUrl.hostname, 'to', info.address)
resolve(info.address)
return undefined
})
.catch(error => {
if (Axios.isCancel(error)) {
return undefined
}
return error as AxiosError
})
})
Promise.all(requests).then(responses => {
const errors = responses.filter(response => response !== undefined) as AxiosError[]
// If all failed, throw an error
if (!complete) {
log.info('All failed DNS HEAD probe responses:')
errors.forEach(response => log.info(formatAxiosError(response)))
reject(new RequestError('All DNS HEAD probes failed. Check logs.'))
return
}
// Check if some failed and warn
if (errors.length > 0) {
log.warn('Some DNS HEAD probes failed:')
errors.forEach(response => log.warn(formatAxiosError(response)))
}
})
})
}
Example #2
Source File: TorrentActions.ts From flood with GNU General Public License v3.0 | 4 votes |
TorrentActions = {
addTorrentsByUrls: (options: AddTorrentByURLOptions): Promise<void> =>
axios.post<TorrentAddResponse>(`${baseURI}api/torrents/add-urls`, options).then(
({data}) => {
if (data.length) {
emitTorrentAddedAlert(data.length);
} else {
emitRequestSentAlert(options.urls.length);
}
},
() => {
emitFailedToAddTorrentAlert(options.urls.length);
},
),
addTorrentsByFiles: (options: AddTorrentByFileOptions): Promise<void> =>
axios.post<TorrentAddResponse>(`${baseURI}api/torrents/add-files`, options).then(
({data}) => {
if (data.length) {
emitTorrentAddedAlert(data.length);
} else {
emitRequestSentAlert(options.files.length);
}
},
() => {
emitFailedToAddTorrentAlert(options.files.length);
},
),
createTorrent: (options: CreateTorrentOptions): Promise<void> =>
axios.post<Blob>(`${baseURI}api/torrents/create`, options, {responseType: 'blob'}).then(
({data}) => {
download(data, (options.name || `${Date.now()}`).concat('.torrent'));
emitTorrentAddedAlert(1);
},
() => {
emitFailedToAddTorrentAlert(1);
},
),
deleteTorrents: (options: DeleteTorrentsOptions): Promise<void> =>
axios.post(`${baseURI}api/torrents/delete`, options).then(
() =>
AlertStore.add({
id: 'alert.torrent.remove',
type: 'success',
count: options.hashes.length,
}),
() =>
AlertStore.add({
id: 'alert.torrent.remove.failed',
type: 'error',
count: options.hashes.length,
}),
),
checkHash: (options: CheckTorrentsOptions): Promise<void> =>
axios.post(`${baseURI}api/torrents/check-hash`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
),
fetchMediainfo: (hash: TorrentProperties['hash'], cancelToken?: CancelToken): Promise<{output: string}> =>
axios
.get<TorrentMediainfoResponse>(`${baseURI}api/torrents/${hash}/mediainfo`, {cancelToken})
.then<{output: string}>((res) => res.data),
fetchTorrentContents: (hash: TorrentProperties['hash']): Promise<Array<TorrentContent> | null> =>
axios.get<Array<TorrentContent>>(`${baseURI}api/torrents/${hash}/contents`).then(
(res) => res.data,
() => null,
),
fetchTorrentPeers: (hash: TorrentProperties['hash']): Promise<Array<TorrentPeer> | null> =>
axios.get<Array<TorrentPeer>>(`${baseURI}api/torrents/${hash}/peers`).then(
(res) => res.data,
() => null,
),
fetchTorrentTrackers: (hash: TorrentProperties['hash']): Promise<Array<TorrentTracker> | null> =>
axios.get<Array<TorrentTracker>>(`${baseURI}api/torrents/${hash}/trackers`).then(
(res) => res.data,
() => null,
),
getTorrentContentsDataPermalink: (hash: TorrentProperties['hash'], indices: number[]): Promise<string> =>
axios
.get(`${ConfigStore.baseURI}api/torrents/${hash}/contents/${indices.join(',')}/token`)
.then(
(res) =>
`${window.location.protocol}//${window.location.host}${
ConfigStore.baseURI
}api/torrents/${hash}/contents/${indices.join(',')}/data?token=${res.data}`,
),
moveTorrents: (options: MoveTorrentsOptions): Promise<void> =>
axios.post(`${baseURI}api/torrents/move`, options).then(
() =>
AlertStore.add({
id: 'alert.torrent.move',
type: 'success',
count: options.hashes.length,
}),
() =>
AlertStore.add({
id: 'alert.torrent.move.failed',
type: 'error',
count: options.hashes.length,
}),
),
reannounce: (options: ReannounceTorrentsOptions): Promise<void> =>
axios.post(`${baseURI}api/torrents/reannounce`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
),
startTorrents: async (options: StartTorrentsOptions): Promise<void> => {
if (options.hashes.length > 0) {
return axios.post(`${baseURI}api/torrents/start`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
);
}
return undefined;
},
stopTorrents: async (options: StopTorrentsOptions): Promise<void> => {
if (options.hashes.length > 0) {
return axios.post(`${baseURI}api/torrents/stop`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
);
}
return undefined;
},
setInitialSeeding: (options: SetTorrentsInitialSeedingOptions): Promise<void> =>
axios.patch(`${baseURI}api/torrents/initial-seeding`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
),
setPriority: (options: SetTorrentsPriorityOptions): Promise<void> =>
axios.patch(`${baseURI}api/torrents/priority`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
),
setSequential: (options: SetTorrentsSequentialOptions): Promise<void> =>
axios.patch(`${baseURI}api/torrents/sequential`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
),
setFilePriority: (hash: TorrentProperties['hash'], options: SetTorrentContentsPropertiesOptions): Promise<void> =>
axios.patch(`${baseURI}api/torrents/${hash}/contents`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
),
setTags: (options: SetTorrentsTagsOptions): Promise<void> =>
axios.patch(`${baseURI}api/torrents/tags`, options).then(
() => UIStore.handleSetTaxonomySuccess(),
() => {
// do nothing.
},
),
setTrackers: (options: SetTorrentsTrackersOptions): Promise<void> =>
axios.patch(`${baseURI}api/torrents/trackers`, options).then(
() => {
// do nothing.
},
() => {
// do nothing.
},
),
}