http#ClientRequestArgs TypeScript Examples

The following examples show how to use http#ClientRequestArgs. 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: request-maker.mixin.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
public sendStream<T = any>(requestParams: IGetHttpRequestArgs & IGetStreamRequestArgs) : Promise<TweetStream<T>> | TweetStream<T> {
    // Pre-request hooks
    if (this.clientSettings.plugins) {
      this.applyPreStreamRequestConfigHooks(requestParams);
    }

    const args = this.getHttpRequestArgs(requestParams);
    const options: Partial<ClientRequestArgs> = {
      method: args.method,
      headers: args.headers,
      agent: this.clientSettings.httpAgent,
    };
    const enableRateLimitSave = requestParams.enableRateLimitSave !== false;
    const enableAutoConnect = requestParams.autoConnect !== false;

    if (args.body) {
      RequestParamHelpers.setBodyLengthHeader(options, args.body);
    }

    const requestData: TRequestFullStreamData = {
      url: args.url,
      options,
      body: args.body,
      rateLimitSaver: enableRateLimitSave ? this.saveRateLimit.bind(this, args.rawUrl) : undefined,
      payloadIsError: requestParams.payloadIsError,
      compression: requestParams.compression ?? this.clientSettings.compression ?? true,
    };

    const stream = new TweetStream<T>(requestData);

    if (!enableAutoConnect) {
      return stream;
    }
    return stream.connect();
  }
Example #2
Source File: request-maker.mixin.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
protected async applyPreRequestHooks(requestParams: IGetHttpRequestArgs, computedParams: IComputedHttpRequestArgs, requestOptions: Partial<ClientRequestArgs>) {
    await this.applyPluginMethod('onBeforeRequest', {
      client: this,
      url: this.getUrlObjectFromUrlString(requestParams.url),
      params: requestParams,
      computedParams,
      requestOptions,
    });
  }
Example #3
Source File: request-maker.mixin.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
protected async applyPostRequestHooks(requestParams: IGetHttpRequestArgs, computedParams: IComputedHttpRequestArgs, requestOptions: Partial<ClientRequestArgs>, response: TwitterResponse<any>) {
    return await this.applyPluginMethod('onAfterRequest', {
      client: this,
      url: this.getUrlObjectFromUrlString(requestParams.url),
      params: requestParams,
      computedParams,
      requestOptions,
      response,
    });
  }
Example #4
Source File: helpers.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
export async function applyResponseHooks(
  this: ClientRequestMaker,
  requestParams: IGetHttpRequestArgs,
  computedParams: IComputedHttpRequestArgs,
  requestOptions: Partial<ClientRequestArgs>,
  error: any,
) {
  let override: TwitterApiPluginResponseOverride | undefined;

  if (error instanceof ApiRequestError || error instanceof ApiPartialResponseError) {
    override = await this.applyPluginMethod('onRequestError', {
      client: this,
      url: this.getUrlObjectFromUrlString(requestParams.url),
      params: requestParams,
      computedParams,
      requestOptions,
      error,
    });
  } else if (error instanceof ApiResponseError) {
    override = await this.applyPluginMethod('onResponseError', {
      client: this,
      url: this.getUrlObjectFromUrlString(requestParams.url),
      params: requestParams,
      computedParams,
      requestOptions,
      error,
    });
  }

  if (override && override instanceof TwitterApiPluginResponseOverride) {
    return override.value;
  }

  return Promise.reject(error);
}
Example #5
Source File: socket.ts    From avalanchejs with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
   * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
   *
   * @param url Defaults to [[MainnetAPI]]
   * @param options Optional
   */
  constructor(
    url: string | import("url").URL = `wss://${MainnetAPI}:443/ext/bc/X/events`,
    options?: WebSocket.ClientOptions | ClientRequestArgs
  ) {
    super(url, options)
  }
Example #6
Source File: ntrip-push-pull.ts    From caster with GNU General Public License v3.0 5 votes vote down vote up
/** RTP request instance processor */
    private static RtpRequestFormer = class RtpRequestFormer extends NtripPushPullTransport.RequestFormer {
        form() {
            this.params.statusVersion = 'HTTP/1.1';
            this.params.path = '/' + this.options.remoteMountpoint;

            if (this.options.ntripVersion == NtripVersion.V2) {
                return new RtpRequestFormer.V2Processor(this).form();
            } else {
                this.transport.error(new Error('RTP only supports NTRIP V2 requests'));
            }
        }

        /** RTP NTRIP v2.0 request instance former */
        private static V2Processor = class V2Processor extends NtripPushPullTransport.RequestFormer {
            private socket?: dgram.Socket;
            private session?: NtripRtpSession;

            form() {
                this.params.headers!['Ntrip-Version'] = 'Ntrip/2.0';
                this.params.headers!['User-Agent'] = 'NTRIP ' + Caster.NAME;
                this.params.headers!['Connection'] = 'keep-alive';

                this.params.createConnection = ((options: ClientRequestArgs, onCreate: (e: Error | undefined, s?: net.Socket) => void) => {
                    this.socket = this.transport.rtpSocket = dgram.createSocket({
                        type: 'udp6',
                        // TODO: https://github.com/nodejs/node/issues/33331
                        lookup: (hostname, options, callback) =>
                            dns.lookup(hostname, 0, (err, address, family) =>
                                callback(err, family === 4 ? '::ffff:' + address : address, family))
                    });

                    this.socket.once('connect', () => onCreate(undefined, this.createInjectionSocket()));
                    this.socket.once('error', (err) => onCreate(err));

                    this.socket.connect(this.options.remote.port, this.options.remote.host);
                }) as any; // Signature of createConnection is incorrect

                if (this.options.mode == 'push') {
                    this.params.method = 'POST';
                    this.setNtripStrHeader();
                } else { // if (this.options.mode == 'pull') {
                    this.params.method = 'GET';
                    this.setNtripGgaHeader();
                }
                this.send();
            }

            private createInjectionSocket(): net.Socket {
                this.session = this.transport.rtpSession = new NtripRtpSession(this.socket!);
                const connection = this.session.httpStream;
                (connection as any).remoteAddress = this.socket?.remoteAddress().address;
                (connection as any).remotePort = this.socket?.remoteAddress().port;
                (connection as any).remoteFamily = this.socket?.remoteAddress().family;

                // Inject as a socket, only remote* properties of net.Socket will be accessed
                return connection as unknown as net.Socket;
            }

            protected response() {
                if (this.res!.statusCode != 200)
                    return this.transport.error(new Error(`Could not connect to caster, response was ${this.res!.statusCode} ${this.res!.statusMessage}`));

                let ssrc = parseInt(this.res!.headers['session'] as string);
                if (isNaN(ssrc)) return this.transport.error(new Error("Caster did not respond with (valid) RTP session code"));

                this.session!.ssrc = ssrc;

                this.connect({
                    type: this.type,
                    stream: this.session!.dataStream
                });

                // Send keep-alive message every 20 seconds to avoid disconnection
                setInterval(() => this.session?.dataStream.write(''), 20000);
            }
        }
    };
Example #7
Source File: request-maker.mixin.ts    From node-twitter-api-v2 with Apache License 2.0 5 votes vote down vote up
/** Send a new request and returns a wrapped `Promise<TwitterResponse<T>`. */
  public async send<T = any>(requestParams: IGetHttpRequestArgs) : Promise<TwitterResponse<T>> {
    // Pre-request config hooks
    if (this.clientSettings.plugins?.length) {
      const possibleResponse = await this.applyPreRequestConfigHooks(requestParams);

      if (possibleResponse) {
        return possibleResponse;
      }
    }

    const args = this.getHttpRequestArgs(requestParams);
    const options: Partial<ClientRequestArgs> = {
      method: args.method,
      headers: args.headers,
      timeout: requestParams.timeout,
      agent: this.clientSettings.httpAgent,
    };
    const enableRateLimitSave = requestParams.enableRateLimitSave !== false;

    if (args.body) {
      RequestParamHelpers.setBodyLengthHeader(options, args.body);
    }

    // Pre-request hooks
    if (this.clientSettings.plugins?.length) {
      await this.applyPreRequestHooks(requestParams, args, options);
    }

    let request = new RequestHandlerHelper<T>({
      url: args.url,
      options,
      body: args.body,
      rateLimitSaver: enableRateLimitSave ? this.saveRateLimit.bind(this, args.rawUrl) : undefined,
      requestEventDebugHandler: requestParams.requestEventDebugHandler,
      compression: requestParams.compression ?? this.clientSettings.compression ?? true,
      forceParseMode: requestParams.forceParseMode,
    })
      .makeRequest();

    if (hasRequestErrorPlugins(this)) {
      request = this.applyResponseErrorHooks(requestParams, args, options, request);
    }

    const response = await request;

    // Post-request hooks
    if (this.clientSettings.plugins?.length) {
      const responseOverride = await this.applyPostRequestHooks(requestParams, args, options, response);

      if (responseOverride) {
        return responseOverride.value as TwitterResponse<T>;
      }
    }

    return response;
  }
Example #8
Source File: request-maker.mixin.ts    From node-twitter-api-v2 with Apache License 2.0 5 votes vote down vote up
protected applyResponseErrorHooks(requestParams: IGetHttpRequestArgs, computedParams: IComputedHttpRequestArgs, requestOptions: Partial<ClientRequestArgs>, promise: Promise<TwitterResponse<any>>) {
    return promise.catch(applyResponseHooks.bind(this, requestParams, computedParams, requestOptions)) as Promise<TwitterResponse<any>>;
  }
Example #9
Source File: index.d.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
constructor(address: string | URL, options?: WebSocket.ClientOptions | ClientRequestArgs);
Example #10
Source File: index.d.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
constructor(
        address: string | URL,
        protocols?: string | string[],
        options?: WebSocket.ClientOptions | ClientRequestArgs,
    );