gaxios

  • Version 7.1.1
  • Published
  • 630 kB
  • 3 dependencies
  • Apache-2.0 license

Install

npm i gaxios
yarn add gaxios
pnpm add gaxios

Overview

A simple common HTTP client specifically for Google APIs and services.

Index

Variables

variable instance

const instance: Gaxios;
  • The default instance used when the request method is directly invoked.

Functions

function request

request: <T>(
opts: GaxiosOptions
) => Promise<import('./common.js').GaxiosResponse<T>>;
  • Make an HTTP request using the given options.

    Parameter opts

    Options for the request

Classes

class Gaxios

class Gaxios implements FetchCompliance {}

    constructor

    constructor(defaults?: GaxiosOptions);
    • The Gaxios class is responsible for making HTTP requests.

      Parameter defaults

      The default set of options to be used for this instance.

    property agentCache

    protected agentCache: Map<string | URL, any>;

      property defaults

      defaults: GaxiosOptions;
      • Default HTTP options that will be used for every HTTP request.

      property interceptors

      interceptors: {
      request: GaxiosInterceptorManager<GaxiosOptionsPrepared>;
      response: GaxiosInterceptorManager<GaxiosResponse>;
      };
      • Interceptors

      method fetch

      fetch: <T = unknown>(
      ...args: Parameters<typeof fetch> | Parameters<Gaxios['request']>
      ) => GaxiosPromise<T>;
      • A compliant API for Gaxios.

        Parameter args

        fetch API or Gaxios#request parameters

        Returns

        the Response with Gaxios-added properties

        Remarks

        This is useful as a drop-in replacement for fetch API usage.

        Example 1

        const gaxios = new Gaxios();
        const myFetch: typeof fetch = (...args) => gaxios.fetch(...args);
        await myFetch('https://example.com');

      method mergeHeaders

      static mergeHeaders: (base?: HeadersInit, ...append: HeadersInit[]) => Headers;
      • Merges headers. If the base headers do not exist a new Headers object will be returned.

        Parameter base

        headers to append/overwrite to

        Parameter append

        headers to append/overwrite with

        Returns

        the base headers instance with merged Headers

        Remarks

        Using this utility can be helpful when the headers are not known to exist: - if they exist as Headers, that instance will be used - it improves performance and allows users to use their existing references to their Headers - if they exist in another form (HeadersInit), they will be used to create a new Headers object - if the base headers do not exist a new Headers object will be created

      method request

      request: <T = any>(opts?: GaxiosOptions) => GaxiosPromise<T>;
      • Perform an HTTP request with the given options.

        Parameter opts

        Set of HTTP options that will be used for this HTTP request.

      class GaxiosError

      class GaxiosError<T = ReturnType<JSON['parse']>> extends Error {}

        constructor

        constructor(
        message: string,
        config: GaxiosOptionsPrepared,
        response?: GaxiosResponse<T>,
        cause?: {}
        );

          property [GAXIOS_ERROR_SYMBOL]

          [GAXIOS_ERROR_SYMBOL]: string;

          property code

          code?: string | number;
          • An error code. Can be a system error code, DOMException error name, or any error's 'code' property where it is a string.

            It is only a number when the cause is sourced from an API-level error (AIP-193).

            Example 1

            'ECONNRESET'

            Example 2

            'TimeoutError'

            Example 3

            500

            See Also

          property config

          config: GaxiosOptionsPrepared;

            property error

            error?: any;

            property response

            response?: GaxiosResponse<T>;

              property status

              status?: number;
              • An HTTP Status code.

                Example 1

                500

                See Also

              method [Symbol.hasInstance]

              static [Symbol.hasInstance]: (instance: unknown) => boolean;
              • Support instanceof operator for GaxiosError across builds/duplicated files.

                See Also

              class GaxiosInterceptorManager

              class GaxiosInterceptorManager<
              T extends GaxiosOptionsPrepared | GaxiosResponse
              > extends Set<GaxiosInterceptor<T> | null> {}
              • Class to manage collections of GaxiosInterceptors for both requests and responses.

              Interfaces

              interface GaxiosInterceptor

              interface GaxiosInterceptor<T extends GaxiosOptionsPrepared | GaxiosResponse> {}
              • Interceptors that can be run for requests or responses. These interceptors run asynchronously.

              property rejected

              rejected?: (err: GaxiosError) => void;
              • Function to be run if the previous call to resolved throws / rejects or the request results in an invalid status as determined by the call to validateStatus.

                Parameter err

                The error thrown from the previously called resolved function.

              property resolved

              resolved?: (configOrResponse: T) => Promise<T>;
              • Function to be run when applying an interceptor.

                Parameter configOrResponse

                The current configuration or response.

                Returns

                {Promise} Promise that resolves to the modified set of options or response.

              interface GaxiosOptions

              interface GaxiosOptions extends RequestInit {}
              • Request options that are used to form the request.

              property adapter

              adapter?: <T = GaxiosResponseData>(
              options: GaxiosOptionsPrepared,
              defaultAdapter: (options: GaxiosOptionsPrepared) => GaxiosPromise<T>
              ) => GaxiosPromise<T>;
              • Optional method to override making the actual HTTP request. Useful for writing tests.

              property agent

              agent?: Agent | ((parsedUrl: URL) => Agent);

                property baseURL

                baseURL?: string | URL;

                  property cert

                  cert?: string;

                    property data

                    data?:
                    | _BodyInit
                    | ArrayBuffer
                    | Blob
                    | Buffer
                    | DataView
                    | File
                    | FormData
                    | ReadableStream
                    | Readable
                    | string
                    | ArrayBufferView
                    | URLSearchParams
                    | {};
                    • The data to send in the RequestInit.body of the request. Objects will be serialized as JSON, except for: - ArrayBuffer - Blob - Buffer (Node.js) - DataView - File - FormData - ReadableStream - stream.Readable (Node.js) - strings - TypedArray (e.g. Uint8Array, BigInt64Array) - URLSearchParams - all other objects where: - headers['Content-Type'] === 'application/x-www-form-urlencoded' (serialized as URLSearchParams)

                      In all other cases, if you would like to prevent application/json as the default Content-Type header you must provide a string or readable stream rather than an object, e.g.:

                      {data: JSON.stringify({some: 'data'})}
                      {data: fs.readFile('./some-data.jpeg')}

                    property errorRedactor

                    errorRedactor?: typeof defaultErrorRedactor | false;
                    • An experimental error redactor.

                      Remarks

                      This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see: - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets

                      Modifiers

                      • @experimental

                    property fetchImplementation

                    fetchImplementation?: typeof fetch;
                    • Implementation of fetch to use when making the API call. Will use fetch by default.

                      Example 1

                      let customFetchCalled = false; const myFetch = (...args: Parameters<typeof fetch>) => { customFetchCalled = true; return fetch(...args); };

                      {fetchImplementation: myFetch};

                    property follow

                    follow?: number;
                    • Deprecated

                      non-spec. Should use 20 if enabled per-spec: https://fetch.spec.whatwg.org/#http-redirect-fetch

                    property key

                    key?: string;

                      property maxContentLength

                      maxContentLength?: number;
                      • The maximum size of the http response Content-Length in bytes allowed.

                      property maxRedirects

                      maxRedirects?: number;
                      • The maximum number of redirects to follow. Defaults to 20.

                        Deprecated

                        non-spec. Should use 20 if enabled per-spec: https://fetch.spec.whatwg.org/#http-redirect-fetch

                      property multipart

                      multipart?: GaxiosMultipartOptions[];
                      • A collection of parts to send as a Content-Type: multipart/related request.

                        This is passed to RequestInit.body.

                      property noProxy

                      noProxy?: (string | URL | RegExp)[];
                      • A list for excluding traffic for proxies. Available via process.env.NO_PROXY as well as a common-separated list of strings - merged with any local noProxy rules.

                        - When provided a string, it is matched by - Wildcard *. and . matching are available. (e.g. .example.com or *.example.com) - When provided a URL, it is matched by the .origin property. - For example, requesting https://example.com with the following noProxys would result in a no proxy use: - new URL('https://example.com') - new URL('https://example.com:443') - The following would be used with a proxy: - new URL('http://example.com:80') - new URL('https://example.com:8443') - When provided a regular expression it is used to match the stringified URL

                        See Also

                      property onUploadProgress

                      onUploadProgress?: (progressEvent: GaxiosResponseData) => void;
                      • Deprecated

                        ignored

                      property params

                      params?: GaxiosResponseData;

                        property paramsSerializer

                        paramsSerializer?: (params: { [index: string]: string | number }) => string;

                        property proxy

                        proxy?: string | URL;
                        • An optional proxy to use for requests. Available via process.env.HTTP_PROXY and process.env.HTTPS_PROXY as well - with a preference for the this config option when multiple are available. The option overrides this.

                          See Also

                        property responseType

                        responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream' | 'unknown';
                        • If the fetchImplementation is native fetch, the stream is a ReadableStream, otherwise readable.Stream

                        property retry

                        retry?: boolean;

                          property retryConfig

                          retryConfig?: RetryConfig;

                            property size

                            size?: number;
                            • Deprecated

                              non-spec. https://github.com/node-fetch/node-fetch/issues/1438

                            property timeout

                            timeout?: number;
                            • A timeout for the request, in milliseconds. No timeout by default.

                            property url

                            url?: string | URL;

                              property validateStatus

                              validateStatus?: (status: number) => boolean;

                                interface GaxiosOptionsPrepared

                                interface GaxiosOptionsPrepared extends GaxiosOptions {}

                                  property headers

                                  headers: Headers;

                                    property url

                                    url: URL;

                                      interface GaxiosResponse

                                      interface GaxiosResponse<T = GaxiosResponseData> extends Response {}

                                        property config

                                        config: GaxiosOptionsPrepared;

                                          property data

                                          data: T;

                                            interface RetryConfig

                                            interface RetryConfig {}
                                            • Gaxios retry configuration.

                                            property currentRetryAttempt

                                            currentRetryAttempt?: number;
                                            • The number of retries already attempted.

                                            property httpMethodsToRetry

                                            httpMethodsToRetry?: string[];
                                            • The HTTP Methods that will be automatically retried. Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']

                                            property maxRetryDelay

                                            maxRetryDelay?: number;

                                              property noResponseRetries

                                              noResponseRetries?: number;
                                              • When there is no response, the number of retries to attempt. Defaults to 2.

                                              property onRetryAttempt

                                              onRetryAttempt?: (err: GaxiosError) => Promise<void> | void;
                                              • Function to invoke when a retry attempt is made.

                                              property retry

                                              retry?: number;
                                              • The number of times to retry the request. Defaults to 3.

                                              property retryBackoff

                                              retryBackoff?: (err: GaxiosError, defaultBackoffMs: number) => Promise<void>;
                                              • Function to invoke which returns a promise. After the promise resolves, the retry will be triggered. If provided, this will be used in-place of the retryDelay

                                              property retryDelay

                                              retryDelay?: number;
                                              • The amount of time to initially delay the retry, in ms. Defaults to 100ms.

                                              property retryDelayMultiplier

                                              retryDelayMultiplier?: number;

                                                property shouldRetry

                                                shouldRetry?: (err: GaxiosError) => Promise<boolean> | boolean;
                                                • Function to invoke which determines if you should retry

                                                property statusCodesToRetry

                                                statusCodesToRetry?: number[][];
                                                • The HTTP response status codes that will automatically be retried. Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]]

                                                property timeOfFirstRequest

                                                timeOfFirstRequest?: number;
                                                • Time that the initial request was made. Users should not set this directly.

                                                property totalTimeout

                                                totalTimeout?: number;
                                                • The length of time to keep retrying in ms. The last sleep period will be shortened as necessary, so that the last retry runs at deadline (and not considerably beyond it). The total time starting from when the initial request is sent, after which an error will be returned, regardless of the retrying attempts made meanwhile. Defaults to Number.MAX_SAFE_INTEGER indicating to effectively ignore totalTimeout.

                                                Type Aliases

                                                type GaxiosPromise

                                                type GaxiosPromise<T = GaxiosResponseData> = Promise<GaxiosResponse<T>>;

                                                  Package Files (4)

                                                  Dependencies (3)

                                                  Dev Dependencies (45)

                                                  Peer Dependencies (0)

                                                  No peer dependencies.

                                                  Badge

                                                  To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                  You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/gaxios.

                                                  • Markdown
                                                    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/gaxios)
                                                  • HTML
                                                    <a href="https://www.jsdocs.io/package/gaxios"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>