https#RequestOptions TypeScript Examples

The following examples show how to use https#RequestOptions. 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: utils.ts    From cardano-launcher with Apache License 2.0 7 votes vote down vote up
/**
 * Sets up the parameters for `http.request` for this Api.
 *
 * @param path - the api route (without leading slash)
 * @param options - extra options to be added to the request.
 * @return an options object suitable for `http.request`
 */
export function makeRequest(
  api: Api,
  path: string,
  options?: ServerOptions | HttpsServerOptions
): RequestOptions {
  return Object.assign(
    {},
    api.requestParams,
    {
      path: api.requestParams.path + path,
    },
    options
  );
}
Example #2
Source File: request-param.helper.ts    From node-twitter-api-v2 with Apache License 2.0 6 votes vote down vote up
static setBodyLengthHeader(options: RequestOptions, body: string | Buffer) {
    options.headers = options.headers ?? {};

    if (typeof body === 'string') {
      options.headers['content-length'] = Buffer.byteLength(body);
    }
    else {
      options.headers['content-length'] = body.length;
    }
  }
Example #3
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();
    });
  }
Example #4
Source File: node-http-post-client.ts    From notion-page-to-html with MIT License 5 votes vote down vote up
async post(url: string, body: Record<string, any>): Promise<HttpResponse> {
    const urlHandler = new URL(url);
    const stringifiedBody = JSON.stringify(body);

    const options: RequestOptions = {
      hostname: urlHandler.hostname,
      path: urlHandler.pathname,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': stringifiedBody.length,
      },
    };

    let status = 504;

    const requestAsPromised: Promise<HttpResponse> = new Promise((resolve, reject) => {
      const req = https
        .request(options, (res) => {
          status = res.statusCode || 504;

          const chunks = new Array<Uint8Array>();

          res.on('data', (chunk) => {
            chunks.push(chunk);
          });

          res.on('end', () => {
            const result = Buffer.concat(chunks).toString('utf8');
            resolve({ status, data: JSON.parse(result) });
          });
        })
        .on('error', (err) => reject(err.message));

      req.write(stringifiedBody);
      req.end();
    });

    return requestAsPromised;
  }
Example #5
Source File: http-client.ts    From sdkgen with MIT License 4 votes vote down vote up
async makeRequest(ctx: PartialDeep<Context> | null, functionName: string, args: unknown): Promise<any> {
    const func = this.astJson.functionTable[functionName];

    if (!func) {
      throw new Error(`Unknown function ${functionName}`);
    }

    const extra: Record<string, unknown> = {};

    for (const [key, value] of this.extra) {
      extra[key] = value;
    }

    const requestBody = JSON.stringify({
      args: encode(this.astJson.typeTable, `${functionName}.args`, func.args, args),
      deviceInfo: ctx?.request?.deviceInfo ?? { id: hostname(), type: "node" },
      extra: {
        ...extra,
        ...ctx?.request?.extra,
      },
      name: functionName,
      requestId: ctx?.request?.id ? ctx.request.id + randomBytes(6).toString("hex") : randomBytes(16).toString("hex"),
      version: 3,
    });

    const options: RequestOptions = {
      hostname: this.baseUrl.hostname,
      method: "POST",
      path: this.baseUrl.pathname,
      port: this.baseUrl.port,
      headers: {
        "content-type": "application/sdkgen",
      },
    };

    const encodedRet = await new Promise<unknown>((resolve, reject) => {
      const req = (this.baseUrl.protocol === "http:" ? httpRequest : httpsRequest)(options, res => {
        let data = "";

        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          try {
            const response = JSON.parse(data) as object;

            if (has(response, "error") && response.error) {
              reject(response.error);
            } else {
              resolve(has(response, "result") ? response.result : null);
            }
          } catch (error) {
            reject({ message: `${error}`, type: "Fatal" });
          }
        });
        res.on("error", error => {
          reject({ message: `${error}`, type: "Fatal" });
        });
        res.on("aborted", () => {
          reject({ message: "Request aborted", type: "Fatal" });
        });
      });

      req.on("error", error => {
        reject({ message: `${error}`, type: "Fatal" });
      });

      req.write(requestBody);
      req.end();
    }).catch(error => {
      if (has(error, "type") && has(error, "message") && typeof error.type === "string" && typeof error.message === "string") {
        const errClass = this.errClasses[error.type];

        if (errClass) {
          const errorJson = this.astJson.errors.find(err => (Array.isArray(err) ? err[0] === error.type : err === error.type));

          if (errorJson) {
            if (Array.isArray(errorJson) && has(error, "data")) {
              throw new errClass(error.message, decode(this.astJson.typeTable, `${errClass.name}.data`, errorJson[1], error.data));
            } else {
              throw new errClass(error.message, undefined);
            }
          }
        }

        throw new (this.errClasses.Fatal as new (message: string) => SdkgenError)(`${error.type}: ${error.message}`);
      } else {
        throw error;
      }
    });

    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return decode(this.astJson.typeTable, `${functionName}.ret`, func.ret, encodedRet);
  }