node-fetch#Headers TypeScript Examples

The following examples show how to use node-fetch#Headers. 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: helpers.ts    From one-platform with MIT License 6 votes vote down vote up
fetchProjects(serverBaseUrl: string) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return fetch(`${serverBaseUrl}/v1/projects`, {
      method: 'GET',
      headers,
      redirect: 'follow',
    })
      .then(handleFetchError)
      .then((res: any) => res.json())
      .then((result: LighthouseProjectType) => result)
      .catch((error: any) => {
        throw new Error(error);
      });
  }
Example #2
Source File: httpClient.ts    From exevo-pan with The Unlicense 6 votes vote down vote up
static async postHtml({
    auctionId,
    pageIndex,
    type,
  }: PostHtmlProps): Promise<string> {
    const headers = new Headers()
    headers.set('X-Requested-With', 'XMLHttpRequest')
    headers.set('User-Agent', new UserAgent().toString())

    const body = new FormData()
    body.append('auctionid', auctionId)
    body.append('currentpage', pageIndex)
    body.append('type', requestTypeKeys[type])

    const response = await fetch(this.POST_ENDPOINT, {
      timeout: REQUEST_TIMEOUT,
      method: 'POST',
      headers,
      body,
    })

    if (response.status !== 200) {
      throw new Error(
        `postHtml() recieved a bad status code [${response.status}]`,
      )
    }

    const data = await response.json()
    const [ajaxObject] = data.AjaxObjects
    return ajaxObject.Data as string
  }
Example #3
Source File: fetch.ts    From open-design-sdk with Apache License 2.0 6 votes vote down vote up
// Streams

export async function getStream<
  PathPattern extends MethodPathPatterns<'get'>,
  Operation extends paths[PathPattern]['get']
>(
  apiRoot: string,
  pathPattern: PathPattern,
  pathParams: PathParams<PathPattern>,
  authInfo: AuthInfo,
  options: {
    console?: Console | null

    cancelToken?: CancelToken | null
  } = {}
): Promise<{
  statusCode: Exclude<OperationStatusCodes<Operation>, 500>
  headers: Headers
  stream: NodeJS.ReadableStream
}> {
  return requestStream(
    'get',
    apiRoot,
    pathPattern,
    pathParams,
    {},
    authInfo,
    options
  )
}
Example #4
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 #5
Source File: alerts.ts    From crypto-alert-telegram-bot with MIT License 6 votes vote down vote up
async function sendMessage(chat_id: string, text: string) {
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');
  const res = await fetch(`https://api.telegram.org/bot${secrets.telegramBotToken}/sendMessage`, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      chat_id,
      text
    }),
  });

  return res.ok;
}
Example #6
Source File: TelemeteryManager.ts    From JSPrismarine with Mozilla Public License 2.0 6 votes vote down vote up
private async tick() {
        if (!this.server) return;

        const body = {
            id: this.id,
            version: `${this.server.getConfig().getVersion()}:${this.server.getQueryManager().git_rev}`,
            online_mode: this.server.getConfig().getOnlineMode(),
            player_count: 0, // TODO
            max_player_count: this.server.getConfig().getMaxPlayers(),
            plugins: this.server
                .getPluginManager()
                ?.getPlugins()
                .map((plugin: PluginFile) => ({
                    name: plugin.getName(),
                    version: plugin.getVersion()
                })),
            tps: this.server.getTPS(),
            uptime: Math.trunc(process.uptime() * 1000),
            node_env: process.env.NODE_ENV
        };

        await Promise.all(
            this.urls.map(async (url) => {
                try {
                    await fetch(`${url}/api/heartbeat`, {
                        method: 'POST',
                        body: JSON.stringify(body),
                        headers: new Headers({
                            'Content-Type': 'application/json'
                        })
                    });
                    this.server.getLogger()?.debug('Sent heartbeat', 'TelemetryManager/tick');
                } catch (error) {
                    this.server.getLogger()?.warn(`Failed to tick: ${url} (${error})`, 'TelemetryManager/tick');
                    this.server.getLogger()?.debug((error as any).stack, 'TelemetryManager/tick');
                }
            })
        );
    }
Example #7
Source File: helpers.ts    From one-platform with MIT License 6 votes vote down vote up
getUserProfile = async (
  rhUUID: string,
): Promise<UserProfileType> => {
  const userQuery = `query GetUsers{
      getUsersBy(rhatUUID:"${rhUUID}") {
          cn
          mail
          uid
          rhatUUID
        }
  }
    `;
  const headers = new Headers();
  const body = JSON.stringify({
    query: userQuery,
    variables: null,
  });
  headers.append('Authorization', `${process.env.GATEWAY_AUTH_TOKEN}`);
  headers.append('Content-Type', 'application/json');
  try {
    const user = await fetch(`${process.env.API_GATEWAY}`, {
      method: 'POST',
      headers,
      body,
    });
    const res = await user.json();
    return res.data.getUsersBy[0];
  } catch (error) {
    throw error as Error;
  }
}
Example #8
Source File: helpers.ts    From one-platform with MIT License 6 votes vote down vote up
/**
   * function to create LH Project
   * @param {PropertyModel} $project: input project document
   * @returns {Object}: Mutated document as object
   */
  createLHProject(project: any) {
    const myHeaders = new Headers();
    myHeaders.append('Content-Type', 'application/json');
    const raw = JSON.stringify(project);

    return fetch(`${process.env.SERVER_BASE_URL}/v1/projects`, {
      method: 'POST',
      headers: myHeaders,
      body: raw,
    })
      .then((response: any) => response.json())
      .catch((error: Error) => {
        Logger.error(error);
      });
  }
Example #9
Source File: helpers.ts    From one-platform with MIT License 6 votes vote down vote up
fetchProjectBranches(serverBaseUrl: string, projectID: string) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return fetch(`${serverBaseUrl}/v1/projects/${projectID}/branches`, {
      method: 'GET',
      headers,
      redirect: 'follow',
    })
      .then(handleFetchError)
      .then((res: any) => res.json())
      .then((result: LighthouseProjectType) => result)
      .catch((error: any) => {
        throw new Error(error);
      });
  }
Example #10
Source File: helpers.ts    From one-platform with MIT License 6 votes vote down vote up
fetchProjectLHR(serverBaseUrl: string, projectID: string, buildID: string) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return fetch(
      `${serverBaseUrl}/v1/projects/${projectID}/builds/${buildID}/runs`,
      {
        method: 'GET',
        headers,
        redirect: 'follow',
      },
    )
      .then(handleFetchError)
      .then((res: any) => {
        if (!res.ok) {
          throw res;
        }
        return res;
      })
      .then((res: any) => res.json())
      .then((results: any) => {
        const scores: LighthouseScoreType[] = [];
        results.forEach((value: any) => {
          const lhr = JSON.parse(value.lhr);
          const data: any = {};
          Object.keys(lhr.categories).forEach((category: any) => {
            data[camelCase(category)] = lhr.categories[category].score;
          });
          scores.push(data);
        });
        return scores;
      })
      .catch((error: any) => {
        throw new Error(error);
      });
  }
Example #11
Source File: helpers.ts    From one-platform with MIT License 6 votes vote down vote up
fetchProjectBuilds(
    serverBaseUrl: string,
    projectID: string,
    branch: string,
    limit: number,
  ) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return fetch(
      `${serverBaseUrl}/v1/projects/${projectID}/builds?branch=${branch}&limit=${limit}`,
      {
        method: 'GET',
        headers,
        redirect: 'follow',
      },
    )
      .then(handleFetchError)
      .then((res: any) => res.json())
      .then((result: LighthouseProjectType) => result)
      .catch((error: any) => {
        throw new Error(error);
      });
  }
Example #12
Source File: helpers.ts    From one-platform with MIT License 6 votes vote down vote up
fetchProjectDetails(serverBaseUrl: string, buildToken: string) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return fetch(`${serverBaseUrl}/v1/projects/lookup`, {
      method: 'POST',
      headers,
      body: JSON.stringify({ token: buildToken }),
      redirect: 'follow',
    })
      .then(handleFetchError)
      .then((res: any) => res.json())
      .then((result: LighthouseProjectType) => result)
      .catch((error: any) => {
        throw new Error(error);
      });
  }
Example #13
Source File: helpers.ts    From one-platform with MIT License 6 votes vote down vote up
fetchProfileFavicon(email: string) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return fetch(`${process.env.GITLAB_URL}/api/v4/avatar?email=${email}`, {
      method: 'GET',
      headers,
    })
      .then(handleFetchError)
      .then((res: any) => res.json())
      .then((result: any) => result)
      .catch((error: any) => {
        throw new Error(error);
      });
  }
Example #14
Source File: TelemeteryManager.ts    From JSPrismarine with Mozilla Public License 2.0 5 votes vote down vote up
public async sendCrashLog(crashlog: Error, urls: string[]) {
        this.server
            .getLogger()
            ?.error(
                "JSPrismarine has crashed, we're now submitting the error to the telemetry service...",
                'TelemetryManager/sendCrashLog'
            );
        this.server.getLogger()?.debug(crashlog?.stack!, 'TelemetryManager/sendCrashLog');

        const body = {
            id: this.generateAnonomizedId(),
            version: `${this.server.getConfig().getVersion()}:${this.server.getQueryManager().git_rev}`,
            error: {
                name: crashlog.name,
                message: crashlog.message,
                stack: crashlog.stack,
                log: this.server.getLogger()?.getLog()
            }
        };

        const links = (
            await Promise.all(
                urls.map(async (url) => {
                    try {
                        const res = await fetch(`${url}/api/error`, {
                            method: 'POST',
                            body: JSON.stringify(body),
                            headers: new Headers({
                                'Content-Type': 'application/json'
                            })
                        });
                        return `${url}/error/${((await res.json()) as any).id}`;
                    } catch (error) {
                        this.server.getLogger()?.debug((error as any).stack, 'TelemetryManager/sendCrashLog');
                    }
                })
            )
        ).filter((a) => a);

        if (!links.length) {
            this.server
                .getLogger()
                ?.error('Failed to submit error to telemetry service!', 'TelemetryManager/sendCrashLog');
            return;
        }

        this.server
            .getLogger()
            ?.error(
                'JSPrismarine has crashed, please report the following url(s) to the maintainers:',
                'TelemetryManager/sendCrashLog'
            );
        links.forEach((url) => {
            this.server.getLogger()?.error(`- ${url}`, 'TelemetryManager/sendCrashLog');
        });
    }
Example #15
Source File: TResponse.ts    From nodetskeleton with MIT License 5 votes vote down vote up
setResponseHeaders(headers: Headers): void {
    this.headers = headers;
  }
Example #16
Source File: TResponse.ts    From nodetskeleton with MIT License 5 votes vote down vote up
headers: Headers | undefined;
Example #17
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;
  }
Example #18
Source File: ethereum.spec.ts    From cloud-cryptographic-wallet with MIT License 5 votes vote down vote up
// @ts-expect-error 何故か型がない
global.Headers = Headers;
Example #19
Source File: headers.ts    From Protoman with MIT License 5 votes vote down vote up
export function convertHeaders(headers: ReadonlyArray<[string, string]>): Headers {
  return headers.reduce((h, [name, value]) => {
    if (name.length > 0) {
      h.append(name, value);
    }
    return h;
  }, new Headers());
}
Example #20
Source File: headers.ts    From Protoman with MIT License 5 votes vote down vote up
export function unconvertHeaders(headers: Headers): ReadonlyArray<[string, string]> {
  const h: [string, string][] = [];
  headers.forEach((value: string, name: string) => h.push([name, value]));
  return h;
}
Example #21
Source File: client.ts    From protobuf-ts with Apache License 2.0 5 votes vote down vote up
globalThis.Headers = Headers as any;
Example #22
Source File: client.ts    From protobuf-ts with Apache License 2.0 5 votes vote down vote up
globalThis.Headers = Headers as any;
Example #23
Source File: client.ts    From protobuf-ts with Apache License 2.0 5 votes vote down vote up
globalThis.Headers = Headers;