https#request TypeScript Examples

The following examples show how to use https#request. 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: execute-pr-actions.ts    From dt-mergebot with MIT License 6 votes vote down vote up
function doRestCall(call: RestMutation): Promise<void> {
    const url = `https://api.github.com/repos/DefinitelyTyped/DefinitelyTyped/${call.op}`;
    const headers = {
        "accept": "application/vnd.github.v3+json",
        "authorization": `token ${process.env.BOT_AUTH_TOKEN}`,
        "user-agent": "dt-mergebot"
    };
    return new Promise((resolve, reject) => {
        const req = request(url, { method: call.method, headers }, reply => {
            const bad = !reply.statusCode || reply.statusCode < 200 || reply.statusCode >= 300;
            if (bad) return reject(`doRestCall failed with a status of ${reply.statusCode}`);
            return resolve();
        });
        req.on("error", reject);
        req.end();
    });
}
Example #2
Source File: request-handler.helper.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
/* Error helpers */

  protected createRequestError(error: Error): ApiRequestError {
    if (TwitterApiV2Settings.debug) {
      TwitterApiV2Settings.logger.log('Request error:', error);
    }

    return new ApiRequestError('Request failed.', {
      request: this.req,
      error,
    });
  }
Example #3
Source File: request-handler.helper.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
protected createPartialResponseError(error: Error, abortClose: boolean): ApiPartialResponseError {
    const res = this.res;
    let message = `Request failed with partial response with HTTP code ${res.statusCode}`;

    if (abortClose) {
      message += ' (connection abruptly closed)';
    } else {
      message += ' (parse error)';
    }

    return new ApiPartialResponseError(message, {
      request: this.req,
      response: this.res,
      responseError: error,
      rawContent: Buffer.concat(this.responseData).toString(),
    });
  }
Example #4
Source File: request-handler.helper.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
protected createResponseError({ res, data, rateLimit, code }: IBuildErrorParams): ApiResponseError {
    if (TwitterApiV2Settings.debug) {
      TwitterApiV2Settings.logger.log(`Request failed with code ${code}, data:`, data);
      TwitterApiV2Settings.logger.log('Response headers:', res.headers);
    }

    // Errors formatting.
    let errorString = `Request failed with code ${code}`;
    if (data?.errors?.length) {
      const errors = data.errors as (ErrorV1 | ErrorV2)[];

      if ('code' in errors[0]) {
        errorString += ' - ' + this.formatV1Errors(errors as ErrorV1[]);
      }
      else {
        errorString += ' - ' + this.formatV2Error(data as ErrorV2);
      }
    }

    return new ApiResponseError(errorString, {
      code,
      data,
      headers: res.headers,
      request: this.req,
      response: res,
      rateLimit,
    });
  }
Example #5
Source File: request-handler.helper.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
protected buildRequest() {
    const url = this.requestData.url;
    const auth = url.username ? `${url.username}:${url.password}` : undefined;
    const headers = this.requestData.options.headers ?? {};

    if (this.requestData.compression === true || this.requestData.compression === 'brotli') {
      headers['accept-encoding'] = 'br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1';
    } else if (this.requestData.compression === 'gzip') {
      headers['accept-encoding'] = 'gzip;q=1, deflate;q=0.5, *;q=0.1';
    } else if (this.requestData.compression === 'deflate') {
      headers['accept-encoding'] = 'deflate;q=1, *;q=0.1';
    }

    if (TwitterApiV2Settings.debug) {
      this.debugRequest();
    }

    this.req = request({
      ...this.requestData.options,
      // Define URL params manually, addresses dependencies error https://github.com/PLhery/node-twitter-api-v2/issues/94
      host: url.hostname,
      port: url.port || undefined,
      path: url.pathname + url.search,
      protocol: url.protocol,
      auth,
      headers,
    });
  }
Example #6
Source File: io.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
async fetch(options: FetchOptions): Promise<string> {
    const maxRetries =
      options.retries === false || options.retries === undefined ? 0 : options.retries === true ? 10 : options.retries;
    for (let retries = maxRetries; retries > 1; retries--) {
      try {
        return await doRequest(options, request, this.agent);
      } catch (err) {
        if (!/EAI_AGAIN|ETIMEDOUT|ECONNRESET/.test((err as Error).message)) {
          throw err;
        }
      }
      await sleep(1);
    }
    return doRequest(options, request, this.agent);
  }
Example #7
Source File: io.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
function doRequest(options: FetchOptions, makeRequest: typeof request, agent?: Agent): Promise<string> {
  return new Promise((resolve, reject) => {
    const req = makeRequest(
      {
        hostname: options.hostname,
        port: options.port,
        path: `/${options.path}`,
        agent,
        method: options.method || "GET",
        headers: options.headers,
        timeout: options.timeout ?? downloadTimeout,
      },
      (res) => {
        let text = "";
        res.on("data", (d: string) => {
          text += d;
        });
        res.on("error", reject);
        res.on("end", () => {
          resolve(text);
        });
      }
    );
    if (options.body !== undefined) {
      req.write(options.body);
    }
    req.end();
  });
}
Example #8
Source File: proxy.ts    From devoirs with MIT License 5 votes vote down vote up
public async request<T>(
    method: Method,
    path: string,
    refreshToken = false
  ): Promise<T> {
    const url = this.baseUrl + path;
    const token = await (refreshToken
      ? this.tokenProvider.refresh()
      : this.tokenProvider.get());

    const options: RequestOptions = {
      method,
      headers: {
        authorization: `Bearer ${token}`,
      },
    };

    return new Promise<T>((resolve, reject) => {
      const callback = (response: IncomingMessage) => {
        let data = '';

        if (response.statusCode === 401) {
          return resolve(this.request(method, path, true));
        }

        if (response.statusCode !== 200) {
          return reject(response);
        }

        response.on('data', (chunk) => (data += chunk));
        response.on('end', () => {
          try {
            resolve(JSON.parse(data)['value'] as T);
          } catch (error) {
            reject(error);
          }
        });
      };

      request(url, options, callback).on('error', reject).end();
    });
  }