http#ClientRequest TypeScript Examples

The following examples show how to use http#ClientRequest. 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-handler.helper.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
protected registerRequestEventDebugHandlers(req: ClientRequest) {
    req.on('close', () => this.requestData.requestEventDebugHandler!('close'));
    req.on('abort', () => this.requestData.requestEventDebugHandler!('abort'));

    req.on('socket', socket => {
      this.requestData.requestEventDebugHandler!('socket', { socket });

      socket.on('error', error => this.requestData.requestEventDebugHandler!('socket-error', { socket, error }));
      socket.on('connect', () => this.requestData.requestEventDebugHandler!('socket-connect', { socket }));
      socket.on('close', withError => this.requestData.requestEventDebugHandler!('socket-close', { socket, withError }));
      socket.on('end', () => this.requestData.requestEventDebugHandler!('socket-end', { socket }));
      socket.on('lookup', (...data) => this.requestData.requestEventDebugHandler!('socket-lookup', { socket, data }));
      socket.on('timeout', () => this.requestData.requestEventDebugHandler!('socket-timeout', { socket }));
    });
  }
Example #2
Source File: tracing.axios-interceptor.ts    From nest-xray with MIT License 6 votes vote down vote up
public responseRejected(): AxiosRejectedInterceptor {
    // Non 2xx Status Code
    // Add error to Subsegment
    // Close Subsegment
    return (error) => {
      if (this.isAxiosError(error)) {
        try {
          const subSegment = this.getSubSegmentFromConfig(error.config);

          if (subSegment) {
            if (error.request && error.response) {
              const request = error.request as ClientRequest;
              const response = {
                statusCode: error.response.status,
              } as IncomingMessage;

              subSegment.addRemoteRequestData(request, response, true);
            } else if (error.config) {
              // Networking Error
              // TODO: Implement addRemoteRequestData
            }

            subSegment.close(error);
          }
        } catch (tracingError) {
          // response error is "more important" than the error from tracing
          // so we swallow the tracing exception (probably TracingNotInitializedException)
        }
      }

      throw error;
    };
  }
Example #3
Source File: RESTError.ts    From dis.ts with MIT License 6 votes vote down vote up
constructor(request: ClientRequest, response: IncomingMessage, payload: ErrorPayload, stack: string, meta: HTTPResponse) {
    super(`[${payload.code}] - ${payload.message}`);
    Object.defineProperty(this, 'request', {
      enumerable: false,
      value: request,
    });
    Object.defineProperty(this, 'response', {
      enumerable: false,
      value: response,
    });
    Object.defineProperty(this, 'statusCode', {
      enumerable: false,
      value: response.statusCode,
    });
    Object.defineProperty(this, 'code', {
      enumerable: false,
      value: payload.code,
    });
    Object.defineProperty(this, 'payload', {
      enumerable: false,
      value: payload,
    });
    Object.defineProperty(this, 'meta', {
      enumerable: false,
      value: meta,
    });
    this.stack = `${this.name}: ${this.message}\n${stack}`;
  }
Example #4
Source File: HTTPResponse.ts    From dis.ts with MIT License 6 votes vote down vote up
constructor(request: ClientRequest, response: IncomingMessage, data: Buffer, stack: string) {
    this.request = request;
    this.headersOut = request.getHeaders();
    this.response = response;
    this.headersIn = response.headers;
    this.data = data;
    if (this.response.statusCode! >= 300) {
      if (this.json?.code) this.error = new RESTError(this.request, this.response, this.json, stack, this);
      else this.error = new HTTPError(this.request, this.response, this.json, stack, this);
    } else {
      this.error = null;
    }
  }
Example #5
Source File: HTTPError.ts    From dis.ts with MIT License 6 votes vote down vote up
constructor(request: ClientRequest, response: IncomingMessage, payload: Record<string | number, unknown>, stack: string, meta: HTTPResponse) {
    super(`${response.statusCode} - ${response.statusMessage}`);
    Object.defineProperty(this, 'request', {
      enumerable: false,
      value: request,
    });
    Object.defineProperty(this, 'response', {
      enumerable: false,
      value: response,
    });
    Object.defineProperty(this, 'statusCode', {
      enumerable: false,
      value: response.statusCode,
    });
    Object.defineProperty(this, 'payload', {
      enumerable: false,
      value: payload,
    });
    Object.defineProperty(this, 'meta', {
      enumerable: false,
      value: meta,
    });
    this.stack = `${this.name}: ${this.message}\n${stack}`;
  }
Example #6
Source File: ntrip-push-pull.ts    From caster with GNU General Public License v3.0 6 votes vote down vote up
class NtripClientRequest extends ClientRequest {
    statusVersion?: string;
    sourceSecret?: string;

    constructor(options: NtripClientRequestOptions, cb?: (res: IncomingMessage) => void) {
        super(options, cb);

        this.statusVersion = options.statusVersion;
        this.sourceSecret = options.sourceSecret;
    }

    // noinspection JSUnusedGlobalSymbols
    /**
     * Internal method that stores the request header.
     * Override to include RTSP in status line.
     *
     * @param firstLine HTTP request status line
     * @param headers HTTP headers
     * @private
     */
    _storeHeader(firstLine: string, headers: OutgoingHttpHeaders) {
        if (this.statusVersion !== undefined)
            firstLine = firstLine.slice(0, firstLine.lastIndexOf(' ') + 1) + this.statusVersion + '\r\n';

        if (this.sourceSecret !== undefined)
            firstLine = firstLine.slice(0, firstLine.indexOf(' ') + 1) +
                    this.sourceSecret + firstLine.slice(firstLine.indexOf(' '));

        // @ts-ignore Call private _storeHeader
        super._storeHeader(firstLine, headers);
    }
}
Example #7
Source File: apibase.ts    From avalanchejs with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
constructor(
    public data: any,
    public headers: any,
    public status: number,
    public statusText: string,
    public request: ClientRequest | XMLHttpRequest
  ) {}
Example #8
Source File: errors.types.ts    From node-twitter-api-v2 with Apache License 2.0 5 votes vote down vote up
abstract request: ClientRequest;
Example #9
Source File: HTTPError.ts    From dis.ts with MIT License 5 votes vote down vote up
request!: ClientRequest;
Example #10
Source File: TweetStream.ts    From node-twitter-api-v2 with Apache License 2.0 5 votes vote down vote up
protected req?: ClientRequest;
Example #11
Source File: HTTPResponse.ts    From dis.ts with MIT License 5 votes vote down vote up
request: ClientRequest;
Example #12
Source File: request-handler.helper.ts    From node-twitter-api-v2 with Apache License 2.0 5 votes vote down vote up
protected req!: ClientRequest;
Example #13
Source File: RESTError.ts    From dis.ts with MIT License 5 votes vote down vote up
request!: ClientRequest;
Example #14
Source File: index.d.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
on(
        event: "unexpected-response",
        listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
    ): this;
Example #15
Source File: index.d.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
once(
        event: "unexpected-response",
        listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
    ): this;
Example #16
Source File: index.d.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
off(
        event: "unexpected-response",
        listener: (this: WebSocket, request: ClientRequest, response: IncomingMessage) => void,
    ): this;
Example #17
Source File: index.d.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
addListener(
        event: "unexpected-response",
        listener: (request: ClientRequest, response: IncomingMessage) => void,
    ): this;
Example #18
Source File: index.d.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
removeListener(
        event: "unexpected-response",
        listener: (request: ClientRequest, response: IncomingMessage) => void,
    ): this;
Example #19
Source File: HttpPlugin.ts    From skywalking-nodejs with Apache License 2.0 4 votes vote down vote up
private interceptClientRequest(module: any, protocol: string) {
    const _request = module.request; // BUG! this doesn't work with "import {request} from http", but haven't found an alternative yet

    module.request = function () {
      const url: URL | string | RequestOptions = arguments[0];

      const { host, pathname } =
        url instanceof URL
          ? url
          : typeof url === 'string'
          ? new URL(url) // TODO: this may throw invalid URL
          : {
              host: (url.host || url.hostname || 'unknown') + ':' + (url.port || 80),
              pathname: url.path || '/',
            };

      const operation = pathname.replace(/\?.*$/g, '');
      const method = arguments[url instanceof URL || typeof url === 'string' ? 1 : 0]?.method || 'GET';
      const span = ignoreHttpMethodCheck(method)
        ? DummySpan.create()
        : ContextManager.current.newExitSpan(operation, Component.HTTP);

      if (span.depth)
        // if we inherited from a higher level plugin then do nothing, higher level should do all the work and we don't duplicate here
        return _request.apply(this, arguments);

      span.start();

      try {
        span.component = Component.HTTP;
        span.layer = SpanLayer.HTTP;
        span.peer = host;

        span.tag(Tag.httpURL(protocol + '://' + host + pathname));
        span.tag(Tag.httpMethod(method));

        const copyStatusAndWrapEmit = (res: any) => {
          span.tag(Tag.httpStatusCode(res.statusCode));

          if (res.statusCode && res.statusCode >= 400) span.errored = true;

          if (res.statusMessage) span.tag(Tag.httpStatusMsg(res.statusMessage));

          wrapEmit(span, res, false);
        };

        const responseCB = function (this: any, res: any) {
          // may wrap callback instead of event because it procs first
          span.resync();

          copyStatusAndWrapEmit(res);

          try {
            if (callback) return callback.apply(this, arguments);
          } catch (err) {
            span.error(err);

            throw err;
          } finally {
            span.async();
          }
        };

        const idxCallback = typeof arguments[2] === 'function' ? 2 : typeof arguments[1] === 'function' ? 1 : 0;
        const callback = arguments[idxCallback];

        if (idxCallback) arguments[idxCallback] = responseCB;

        let arg0 = arguments[0];
        const expect = arg0.headers && (arg0.headers.Expect || arg0.headers.expect);

        if (expect === '100-continue') {
          span.inject().items.forEach((item) => {
            arg0.headers[item.key] = item.value;
          });
        }

        const req: ClientRequest = _request.apply(this, arguments);

        span
          .inject()
          .items.filter((item) => expect != '100-continue')
          .forEach((item) => req.setHeader(item.key, item.value));

        wrapEmit(span, req, true, 'close');

        req.on('timeout', () => span.log('Timeout', true));
        req.on('abort', () => span.log('Abort', (span.errored = true)));

        if (!idxCallback) req.on('response', copyStatusAndWrapEmit);

        span.async();

        return req;
      } catch (err) {
        span.error(err);
        span.stop();

        throw err;
      }
    };
  }