axios#ResponseType TypeScript Examples
The following examples show how to use
axios#ResponseType.
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: Client.ts From fnbr.js with MIT License | 6 votes |
/**
* Downloads a file from the CDN (used for replays)
* @param url The URL of the file to download
* @param responseType The response type
*/
private async downloadReplayCDNFile(url: string, responseType: ResponseType) {
const fileLocationInfo = await this.http.sendEpicgamesRequest(true, 'GET', url, 'fortnite');
if (fileLocationInfo.error) return fileLocationInfo;
const file = await this.http.send('GET', (Object.values(fileLocationInfo.response.files)[0] as any).readLink, undefined, undefined, undefined, responseType);
if (file.response) return { response: file.response.data };
return file;
}
Example #2
Source File: endpoints.ts From homebridge-nest-cam with GNU General Public License v3.0 | 5 votes |
/**
* Send a generic api request
* @param {string} accessToken The token used to authenticate request
* @param {string} hostname The base uri to send the request
* @param {string} endpoint The endpoint to send the request
* @param {Method} method Usually 'GET' or 'POST'
* @param {ResponseType} type The type of return object (Usually 'json')
* @param {string} contentType The content type of the request
* @param {boolean} timeout Whether the request should timeout or not
* @param {any} data The body of the request or null if a 'GET'
*/
async sendRequest(
accessToken: string | undefined,
hostname: string,
endpoint: string,
method: Method,
type: ResponseType = 'json',
contentType = '',
timeout = true,
data?: any,
): Promise<any> {
const headers: any = {
'User-Agent': NestEndpoints.USER_AGENT_STRING,
Referer: this.NEST_API_HOSTNAME,
};
if (contentType) {
headers['Content-Type'] = contentType;
}
if (accessToken) {
headers.Authorization = `Basic ${accessToken}`;
}
const url = hostname + endpoint;
const req: AxiosRequestConfig = {
method,
url,
data,
headers,
responseType: type,
timeout: timeout ? API_TIMEOUT_SECONDS * 1000 : undefined,
};
return (await axios(req)).data;
}
Example #3
Source File: skydb.ts From skynet-js with MIT License | 5 votes |
// =========
// Raw Bytes
// =========
/**
* Gets the raw bytes corresponding to the publicKey and dataKey. The caller is responsible for setting any metadata in the bytes.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The returned bytes.
* @throws - Will throw if the returned signature does not match the returned entry, or if the skylink in the entry is invalid.
* @deprecated - Use of this method may result in data race bugs. Reworking your application to use `client.dbV2.getRawBytes` is recommended.
*/
export async function getRawBytes(
this: SkynetClient,
publicKey: string,
dataKey: string,
// TODO: Take a new options type?
customOptions?: CustomGetJSONOptions
): Promise<RawBytesResponse> {
validatePublicKey("publicKey", publicKey, "parameter");
validateString("dataKey", dataKey, "parameter");
validateOptionalObject("customOptions", customOptions, "parameter", DEFAULT_GET_JSON_OPTIONS);
const opts = {
...DEFAULT_GET_JSON_OPTIONS,
...this.customOptions,
...customOptions,
};
// Lookup the registry entry.
const getEntryOpts = extractOptions(opts, DEFAULT_GET_ENTRY_OPTIONS);
const entry = await getSkyDBRegistryEntry(this, publicKey, dataKey, getEntryOpts);
if (entry === null) {
return { data: null, dataLink: null };
}
// Determine the data link.
// TODO: Can this still be an entry link which hasn't yet resolved to a data link?
const { rawDataLink, dataLink } = parseDataLink(entry.data, false);
// If a cached data link is provided and the data link hasn't changed, return.
if (checkCachedDataLink(rawDataLink, opts.cachedDataLink)) {
return { data: null, dataLink };
}
// Download the data in the returned data link.
const downloadOpts = {
...extractOptions(opts, DEFAULT_DOWNLOAD_OPTIONS),
responseType: "arraybuffer" as ResponseType,
};
const { data: buffer } = await this.getFileContent<ArrayBuffer>(dataLink, downloadOpts);
return { data: new Uint8Array(buffer), dataLink };
}
Example #4
Source File: skydb_v2.ts From skynet-js with MIT License | 5 votes |
// =========
// Raw Bytes
// =========
/**
* Gets the raw bytes corresponding to the publicKey and dataKey. The caller is responsible for setting any metadata in the bytes.
*
* If the data was found, we update the cached revision number for the entry.
* See getJSON for behavior in other cases.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The returned bytes.
* @throws - Will throw if the returned signature does not match the returned entry, or if the skylink in the entry is invalid.
*/
export async function getRawBytes(
this: SkynetClient,
publicKey: string,
dataKey: string,
// TODO: Take a new options type?
customOptions?: CustomGetJSONOptions
): Promise<RawBytesResponse> {
validatePublicKey("publicKey", publicKey, "parameter");
validateString("dataKey", dataKey, "parameter");
validateOptionalObject("customOptions", customOptions, "parameter", DEFAULT_GET_JSON_OPTIONS);
const opts = {
...DEFAULT_GET_JSON_OPTIONS,
...this.customOptions,
...customOptions,
};
// Immediately fail if the mutex is not available.
return await this.dbV2.revisionNumberCache.withCachedEntryLock(publicKey, dataKey, async (cachedRevisionEntry) => {
// Lookup the registry entry.
const getEntryOpts = extractOptions(opts, DEFAULT_GET_ENTRY_OPTIONS);
const entry = await getSkyDBRegistryEntryAndUpdateCache(
this,
publicKey,
dataKey,
cachedRevisionEntry,
getEntryOpts
);
if (entry === null) {
return { data: null, dataLink: null };
}
// Determine the data link.
// TODO: Can this still be an entry link which hasn't yet resolved to a data link?
const { rawDataLink, dataLink } = parseDataLink(entry.data, false);
// If a cached data link is provided and the data link hasn't changed, return.
if (checkCachedDataLink(rawDataLink, opts.cachedDataLink)) {
return { data: null, dataLink };
}
// Download the data in the returned data link.
const downloadOpts = {
...extractOptions(opts, DEFAULT_DOWNLOAD_OPTIONS),
responseType: "arraybuffer" as ResponseType,
};
const { data: buffer } = await this.getFileContent<ArrayBuffer>(dataLink, downloadOpts);
return { data: new Uint8Array(buffer), dataLink };
});
}
Example #5
Source File: HTTP.ts From fnbr.js with MIT License | 5 votes |
/**
* Sends a HTTP request
* @param method The HTTP method
* @param url The uri
* @param headers The headers
* @param body The body
* @param form The form
* @param responseType The axios response type
* @param retries How many times this request has been retried
*/
public async send(method: Method, url: string, headers: KeyValuePair = {}, body?: any, form?: KeyValuePair, responseType?: ResponseType, retries = 0): Promise<HTTPResponse> {
let data;
if (body) data = body;
else if (form) {
const urlSearchParams = new URLSearchParams();
for (const key of Object.keys(form)) {
urlSearchParams.append(key, form[key]);
}
data = urlSearchParams;
}
const finalHeaders = headers;
if (!finalHeaders['Accept-Language']) finalHeaders['Accept-Language'] = this.client.config.language;
const reqStartTime = Date.now();
try {
const response = await this.axios.request({
method,
url,
headers: finalHeaders,
data,
responseType,
});
this.client.debug(`${method} ${url} (${((Date.now() - reqStartTime) / 1000).toFixed(2)}s): `
+ `${response.status} ${response.statusText || '???'}`, 'http');
return { response };
} catch (err: any) {
this.client.debug(`${method} ${url} (${((Date.now() - reqStartTime) / 1000).toFixed(2)}s): `
+ `${err.response?.status || '???'} ${err.response?.statusText || '???'}`, 'http');
const errResponse = (err as AxiosError).response;
if (errResponse?.status.toString().startsWith('5') && retries < this.client.config.restRetryLimit) {
return this.send(method, url, headers, body, form, responseType, retries + 1);
}
if (errResponse && (errResponse.status === 429 || (errResponse?.data as any)?.errorCode === 'errors.com.epicgames.common.throttled')) {
const retryAfter = parseInt(errResponse.headers['Retry-After'] || (errResponse.data as any).messageVars[0], 10);
if (!Number.isNaN(retryAfter)) {
const sleepTimeout = (retryAfter * 1000) + 500;
await new Promise((res) => {
setTimeout(res, sleepTimeout);
});
return this.send(method, url, headers, body, form, responseType);
}
}
return { error: err as AxiosError };
}
}