node-fetch#RequestInit TypeScript Examples

The following examples show how to use node-fetch#RequestInit. 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 mtcute with GNU Lesser General Public License v3.0 7 votes vote down vote up
export async function fetchRetry(
    url: string,
    params?: RequestInit,
    retries = 5
): Promise<string> {
    while (true) {
        try {
            return await fetch(url, params).then((i) => i.text())
        } catch (e) {
            if (!retries--) {
                throw e
            }
        }
    }
}
Example #2
Source File: test-helpers.ts    From livepeer-com with MIT License 7 votes vote down vote up
async fetch(path: string, args: RequestInit = {}) {
    let headers = args.headers || {};
    if (this.apiKey) {
      headers = {
        authorization: `Bearer ${this.apiKey}`,
        ...headers,
      };
    }
    if (this.jwtAuth) {
      headers = {
        authorization: `JWT ${this.jwtAuth}`,
        ...headers,
      };
    }
    if (this.basicAuth) {
      const basic64 = Buffer.from(this.basicAuth).toString("base64");
      headers = {
        authorization: `Basic ${basic64}`,
        ...headers,
      };
    }
    const res = await fetch(
      `${this.server.host}${this.server.httpPrefix}${path}`,
      {
        ...args,
        headers,
      }
    );
    return res;
  }
Example #3
Source File: request.ts    From Wikipedia with MIT License 6 votes vote down vote up
// Makes a request to rest api endpoint
export async function makeRestRequest(path: string, redirect = true): Promise<any> {
    try {
        if (!redirect) {
            path += '?redirect=false'
        }
        const options: RequestInit = {
            headers: {
                'User-Agent': USER_AGENT
            }
        }
        const response = await fetch(encodeURI(REST_API_URL + path), options);

        let result = await response.text();
        try {
            result = JSON.parse(result);
        }
        finally {
            return result;
        }
    } catch (error) {
        throw new wikiError(error);
    }
}
Example #4
Source File: rest.ts    From magic-admin-js with MIT License 6 votes vote down vote up
/**
 * Performs a `fetch` to the given URL with the configured `init` object.
 */
async function emitRequest<TResponse extends any = {}>(url: string, init?: RequestInit): Promise<Partial<TResponse>> {
  const json: MagicAPIResponse<TResponse> = await fetch(url, init)
    .then(res => res.json())
    .catch(err => {
      throw createServiceError(err);
    });

  if (json.status !== 'ok') {
    throw createServiceError(json);
  }

  return json.data ?? {};
}
Example #5
Source File: test-helpers.ts    From livepeer-com with MIT License 6 votes vote down vote up
async patch(path: string, data: any) {
    const params: RequestInit = {
      method: "PATCH",
    };
    if (data) {
      params.headers = {
        "content-type": "application/json",
      };
      params.body = JSON.stringify(data);
    }
    return await this.fetch(path, params);
  }
Example #6
Source File: test-helpers.ts    From livepeer-com with MIT License 6 votes vote down vote up
async put(path: string, data: any) {
    const params: RequestInit = {
      method: "PUT",
    };
    if (data) {
      params.headers = {
        "content-type": "application/json",
      };
      params.body = JSON.stringify(data);
    }
    return await this.fetch(path, params);
  }
Example #7
Source File: test-helpers.ts    From livepeer-com with MIT License 6 votes vote down vote up
async post(path: string, data?: any) {
    const params: RequestInit = {
      method: "POST",
    };
    if (data) {
      params.headers = {
        "content-type": "application/json",
      };
      params.body = JSON.stringify(data);
    }
    return await this.fetch(path, params);
  }
Example #8
Source File: test-helpers.ts    From livepeer-com with MIT License 6 votes vote down vote up
async delete(path: string, data?: any) {
    const params: RequestInit = {
      method: "DELETE",
    };
    if (data) {
      params.headers = {
        "content-type": "application/json",
      };
      params.body = JSON.stringify(data);
    }
    return await this.fetch(path, params);
  }
Example #9
Source File: eos.ts    From coin-wallets with Apache License 2.0 6 votes vote down vote up
// https://docs.dfuse.io/guides/eosio/tutorials/write-chain/
function createCustomizedFetch(
  client: DfuseClient,
): (input: string | Request, init: RequestInit) => Promise<Response> {
  const customizedFetch = async (input: string | Request, init: RequestInit): Promise<Response> => {
    if (init.headers === undefined) {
      init.headers = {}; // eslint-disable-line no-param-reassign
    }

    // This is highly optimized and cached, so while the token is fresh, this is very fast
    const apiTokenInfo = await client.getTokenInfo();

    const headers = init.headers as { [name: string]: string };
    headers.Authorization = `Bearer ${apiTokenInfo.token}`;
    headers['X-Eos-Push-Guarantee'] = 'in-block';

    return fetch(input, init);
  };

  return customizedFetch;
}
Example #10
Source File: index.ts    From nodetskeleton with MIT License 6 votes vote down vote up
private buildRequest(
    url: string,
    method: string,
    body?: BodyType,
    headers?: Headers,
    options?: RequestInit,
  ): Request {
    if (!options) options = {};
    options["method"] = method;
    if (body) options["body"] = body;
    if (headers) options["headers"] = headers;

    return new Request(url, options);
  }
Example #11
Source File: fetch-client.service.ts    From loopback4-microservice-catalog with MIT License 6 votes vote down vote up
async get<T>(url: string, req: RequestInit = {}): Promise<T> {
    const { transformResponse, willSendRequest } = this;

    const args = await this.buildRequestArgs(
      url,
      HttpMethod.Get,
      undefined,
      req,
    );

    if (willSendRequest) {
      await willSendRequest(args.url, args.request);
    }

    const response = await fetch(args.url, args.request);

    return transformResponse(response);
  }
Example #12
Source File: request.ts    From Wikipedia with MIT License 6 votes vote down vote up
// Makes a request to legacy php endpoint
async function makeRequest(params: any, redirect = true): Promise<any> {
    try {
        const search = { ...params }
        search['format'] = 'json';
        if (redirect) {
            search['redirects'] = '';
        }
        if (!params.action)
            search['action'] = "query";
        search['origin'] = '*';
        const options: RequestInit = {
            headers: {
                'User-Agent': USER_AGENT,
            }
        }
        let searchParam = '';
        Object.keys(search).forEach(key => {
            searchParam += `${key}=${search[key]}&`
        });
        const response = await fetch(encodeURI(API_URL + searchParam), options);
        const result = await response.json();
        return result;
    } catch (error) {
        throw new wikiError(error);
    }
}
Example #13
Source File: gerrit.ts    From backstage with Apache License 2.0 6 votes vote down vote up
createGerritProject = async (
  config: GerritIntegrationConfig,
  options: {
    projectName: string;
    parent: string;
    owner: string;
    description: string;
  },
): Promise<void> => {
  const { projectName, parent, owner, description } = options;

  const fetchOptions: RequestInit = {
    method: 'PUT',
    body: JSON.stringify({
      parent,
      description,
      owners: [owner],
      create_empty_commit: false,
    }),
    headers: {
      ...getGerritRequestOptions(config).headers,
      'Content-Type': 'application/json',
    },
  };
  const response: Response = await fetch(
    `${config.baseUrl}/a/projects/${encodeURIComponent(projectName)}`,
    fetchOptions,
  );
  if (response.status !== 201) {
    throw new Error(
      `Unable to create repository, ${response.status} ${
        response.statusText
      }, ${await response.text()}`,
    );
  }
}
Example #14
Source File: bitbucketServer.ts    From backstage with Apache License 2.0 6 votes vote down vote up
performEnableLFS = async (opts: {
  authorization: string;
  host: string;
  project: string;
  repo: string;
}) => {
  const { authorization, host, project, repo } = opts;

  const options: RequestInit = {
    method: 'PUT',
    headers: {
      Authorization: authorization,
    },
  };

  const { ok, status, statusText } = await fetch(
    `https://${host}/rest/git-lfs/admin/projects/${project}/repos/${repo}/enabled`,
    options,
  );

  if (!ok)
    throw new Error(
      `Failed to enable LFS in the repository, ${status}: ${statusText}`,
    );
}
Example #15
Source File: fetch-client.service.ts    From loopback4-microservice-catalog with MIT License 6 votes vote down vote up
/* eslint-disable  @typescript-eslint/no-explicit-any */
  async post<T>(url: string, body?: any, req: RequestInit = {}): Promise<T> {
    const { transformResponse, willSendRequest } = this;

    const args = await this.buildRequestArgs(url, HttpMethod.Post, body, req);

    if (willSendRequest) {
      await willSendRequest(args.url, args.request);
    }

    const response = await fetch(args.url, args.request);

    return transformResponse(response);
  }
Example #16
Source File: fetch-client.service.ts    From loopback4-microservice-catalog with MIT License 6 votes vote down vote up
/* eslint-disable  @typescript-eslint/no-explicit-any */
  async put<T>(url: string, body?: any, req: RequestInit = {}): Promise<T> {
    const { transformResponse, willSendRequest } = this;

    const args = await this.buildRequestArgs(url, HttpMethod.Put, body, req);

    if (willSendRequest) {
      await willSendRequest(args.url, args.request);
    }

    const response = await fetch(args.url, args.request);

    return transformResponse(response);
  }
Example #17
Source File: bitbucket.ts    From backstage with Apache License 2.0 6 votes vote down vote up
performEnableLFS = async (opts: {
  authorization: string;
  host: string;
  project: string;
  repo: string;
}) => {
  const { authorization, host, project, repo } = opts;

  const options: RequestInit = {
    method: 'PUT',
    headers: {
      Authorization: authorization,
    },
  };

  const { ok, status, statusText } = await fetch(
    `https://${host}/rest/git-lfs/admin/projects/${project}/repos/${repo}/enabled`,
    options,
  );

  if (!ok)
    throw new Error(
      `Failed to enable LFS in the repository, ${status}: ${statusText}`,
    );
}
Example #18
Source File: fetch-client.service.ts    From loopback4-microservice-catalog with MIT License 6 votes vote down vote up
/* eslint-disable  @typescript-eslint/no-explicit-any */
  async patch<T>(url: string, body?: any, req: RequestInit = {}): Promise<T> {
    const { transformResponse, willSendRequest } = this;

    const args = await this.buildRequestArgs(url, HttpMethod.Patch, body, req);

    if (willSendRequest) {
      await willSendRequest(args.url, args.request);
    }

    const response = await fetch(args.url, args.request);

    return transformResponse(response);
  }
Example #19
Source File: fetch-client.service.ts    From loopback4-microservice-catalog with MIT License 6 votes vote down vote up
async delete<T>(url: string, req: RequestInit = {}): Promise<T> {
    const { transformResponse, willSendRequest } = this;

    const args = await this.buildRequestArgs(
      url,
      HttpMethod.Delete,
      undefined,
      req,
    );

    if (willSendRequest) {
      await willSendRequest(args.url, args.request);
    }

    const response = await fetch(args.url, args.request);

    return transformResponse(response);
  }
Example #20
Source File: fetch-client.service.ts    From loopback4-microservice-catalog with MIT License 6 votes vote down vote up
/* eslint-disable  @typescript-eslint/no-explicit-any */
  private async buildRequestArgs(
    url: string,
    method: HttpMethod,
    body: any,
    opts: RequestInit,
  ): Promise<{ url: string; request: RequestInit }> {
    const args = {
      url: urlJoin(this.baseUrl, url),
      request: {
        ...this.baseOptions,
        method,
        body: this.useJson && body ? JSON.stringify(body) : body,
        ...opts,
        headers: {
          ...this.baseHeaders,
          ...opts.headers,
        },
      },
    };

    return args;
  }
Example #21
Source File: GithubUrlReader.ts    From backstage with Apache License 2.0 6 votes vote down vote up
private async fetchResponse(
    url: string | URL,
    init: RequestInit,
  ): Promise<Response> {
    const urlAsString = url.toString();

    const response = await fetch(urlAsString, init);

    if (!response.ok) {
      const message = `Request failed for ${urlAsString}, ${response.status} ${response.statusText}`;
      if (response.status === 404) {
        throw new NotFoundError(message);
      }
      throw new Error(message);
    }

    return response;
  }
Example #22
Source File: GithubUrlReader.ts    From backstage with Apache License 2.0 6 votes vote down vote up
private async doReadTree(
    archiveUrl: string,
    sha: string,
    subpath: string,
    init: RequestInit,
    options?: ReadTreeOptions,
  ): Promise<ReadTreeResponse> {
    // archive_url looks like "https://api.github.com/repos/owner/repo/{archive_format}{/ref}"
    const archive = await this.fetchResponse(
      archiveUrl
        .replace('{archive_format}', 'tarball')
        .replace('{/ref}', `/${sha}`),
      init,
    );

    return await this.deps.treeResponseFactory.fromTarArchive({
      // TODO(Rugvip): Underlying implementation of fetch will be node-fetch, we probably want
      //               to stick to using that in exclusively backend code.
      stream: archive.body as unknown as Readable,
      subpath,
      etag: sha,
      filter: options?.filter,
    });
  }
Example #23
Source File: fetch-client.service.ts    From loopback4-microservice-catalog with MIT License 5 votes vote down vote up
readonly baseOptions: Omit<RequestInit, 'headers'>;
Example #24
Source File: fetch.ts    From open-design-sdk with Apache License 2.0 5 votes vote down vote up
async function requestStream<
  PathPattern extends string,
  Operation extends IOperation
>(
  method: string,
  apiRoot: string,
  pathPattern: PathPattern,
  pathParams: PathParams<PathPattern>,
  requestParams: Omit<RequestInit, 'method'> = {},
  authInfo: AuthInfo | null,
  options: {
    console?: Console | null
    cancelToken?: CancelToken | null
  } = {}
) {
  const path = populatePathPattern(pathPattern, pathParams)

  const res = await fetch(`${apiRoot}${path}`, {
    method,
    ...requestParams,
    headers: {
      ...(authInfo ? { 'Authorization': `Bearer ${authInfo.token}` } : {}),
      ...(requestParams.headers || {}),
    },
    console: options.console || console,
    cancelToken: options.cancelToken || null,
  })
  options.cancelToken?.throwIfCancelled()

  if (res.status === 500) {
    throw new Error('Server Error')
  }

  if (!res.body) {
    throw new Error('Response body stream not available')
  }

  return {
    statusCode: res.status as Exclude<OperationStatusCodes<Operation>, 500>,
    headers: res.headers,
    stream: res.body,
  }
}
Example #25
Source File: fetch.ts    From open-design-sdk with Apache License 2.0 5 votes vote down vote up
// General

async function request<
  PathPattern extends string,
  Operation extends IOperation
>(
  method: string,
  apiRoot: string,
  pathPattern: PathPattern,
  pathParams: PathParams<PathPattern>,
  requestParams: Omit<RequestInit, 'method'> = {},
  authInfo: AuthInfo | null,
  options: {
    console?: Console | null
    cancelToken?: CancelToken | null
  } = {}
) {
  const path = populatePathPattern(pathPattern, pathParams)
  const res = await fetch(`${apiRoot}${path}`, {
    method,
    ...requestParams,
    headers: {
      ...(authInfo ? { 'Authorization': `Bearer ${authInfo.token}` } : {}),
      ...(requestParams.headers || {}),
    },
    console: options.console || console,
    cancelToken: options.cancelToken || null,
  })
  options.cancelToken?.throwIfCancelled()

  const body = await res.json()
  options.cancelToken?.throwIfCancelled()

  if (res.status === 500) {
    throw new Error('Server Error')
  }

  return {
    statusCode: res.status,
    headers: res.headers,
    body,
  } as Exclude<OperationResponse<Operation>, { statusCode: 500 }>
}
Example #26
Source File: fetch.ts    From open-design-sdk with Apache License 2.0 5 votes vote down vote up
export async function fetch(
  url: string,
  params: Omit<RequestInit, 'signal'> & {
    console?: Console
    cancelToken?: CancelToken | null
  } = {}
): ReturnType<typeof fetchInternal> {
  const {
    console: fetchConsole = console,
    cancelToken,
    ...requestInit
  } = params

  const method = requestInit.method?.toUpperCase() || 'GET'
  fetchConsole.debug('API:', method, url, '...')

  const signal = cancelToken?.signal
  try {
    const res = await fetchInternal(url, { ...requestInit, signal })

    const logData = [
      'API:',
      method,
      url,
      '->',
      `${res.status} ${res.statusText}`,
    ]
    if (res.status >= 400) {
      fetchConsole.error(...logData)
    } else {
      fetchConsole.info(...logData)
    }

    return res
  } catch (err) {
    const typedErr = err as Error & { type?: string }
    if (typedErr.type === 'AbortError' && cancelToken) {
      cancelToken.throwIfCancelled()
    }
    throw err
  }
}
Example #27
Source File: test-helpers.ts    From web with MIT License 5 votes vote down vote up
export async function fetchText(url: string, init?: RequestInit) {
  const response = await fetch(url, init);

  expect(response.status).to.equal(200);
  return response.text();
}
Example #28
Source File: HttpClient.ts    From l2beat with MIT License 5 votes vote down vote up
fetch(url: string, init?: RequestInit): Promise<Response> {
    return fetch(url, init)
  }
Example #29
Source File: index.ts    From nodetskeleton with MIT License 5 votes vote down vote up
async send<R, E>(
    url: string,
    {
      method = this.Methods.GET,
      body,
      headers,
      options,
      serializationMethod = this.SerializationMethod.json,
    }: {
      method?: string;
      body?: BodyType;
      headers?: Headers;
      options?: RequestInit;
      serializationMethod?: string;
    },
  ): Promise<TResponse<R, E>> {
    const request = this.buildRequest(url, method, body, headers, options);
    const result = new TResponse<R, E>();
    try {
      const response = await fetch(url, request);
      if (response.ok) {
        result.setResponse(await this.processResponseData<R>(response, serializationMethod));
      } else {
        const errorResponse = await this.processErrorResponse<E>(response);
        if (errorResponse[1] === SERIALIZED) {
          result.setErrorMessage(
            response?.statusText || appMessages.get(appMessages.keys.UNKNOWN_RESPONSE_STATUS),
          );
          result.setErrorResponse(errorResponse[0] as E);
        } else {
          result.setErrorMessage(response.statusText);
          result.setErrorResponse(errorResponse[0] as E);
        }
      }
      result.setStatusCode(response.status);
    } catch (error) {
      result.setErrorMessage((error as Error).message);
      result.setStatusCode(httpStatus.INTERNAL_SERVER_ERROR);
      result.setError(error as Error);
    }
    return result;
  }