How to use abort-controller - 10 common examples

To help you get started, we’ve selected a few abort-controller examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github alleyinteractive / irving / packages / core / services / fetchComponents.js View on Github external
search,
  cookie = '',
  context = CONTEXT_PAGE
) {
  const query = queryString.stringify({
    path,
    context,
    ...getExtraQueryParams(),
    ...queryString.parse(search),
    ...getQueryParamsFromCookies(cookie),
  });
  const apiUrl = `${process.env.API_ROOT_URL}/components?${query}`;

  // Create abort controller and set timeout to abort fetch call.
  // Default timeout is 10s, but can be configured with env var.
  const controller = new AbortController();
  const timeout = setTimeout(
    () => controller.abort(),
    env.FETCH_TIMEOUT || 10000
  );

  // Set up fetch options.
  const options = {
    headers: {
      Accept: 'application/json',
    },
    credentials: 'include', // Support XHR with basic auth.
    signal: controller.signal,
  };
  const response = await fetch(apiUrl, options);

  // Clear timeout once response is returned (no matter what it is).
github the-control-group / authx / packages / http-proxy-resource / src / AuthXKeyCache.ts View on Github external
protected _fetch = async (): Promise => {
    this._fetchTimeout = null;

    // Don't fetch unless the cache is active.
    if (!this.active) {
      return;
    }

    this._fetchAbortController = new AbortController();
    this._fetchAbortTimeout = setTimeout(() => {
      if (this._fetchAbortController) {
        this._fetchAbortController.abort();
      }
    }, (this._config.authxPublicKeyRefreshRequestTimeout || 30) * 1000);

    try {
      // Fetch the keys from AuthX.
      // FIXME: This should not need to be cast through any. See:
      // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/35636
      const response = await (
        await fetch(this._config.authxUrl + "/graphql", {
          signal: this._fetchAbortController.signal,
          method: "POST",
          headers: {
            "Content-Type": "application/json"
github the-control-group / authx / packages / http-proxy-authorization / src / index.ts View on Github external
}

    // Clear any refresh timeout for this token.
    if (
      this._refreshTimeouts[refreshToken] &&
      this._refreshTimeouts[refreshToken][hash]
    ) {
      clearTimeout(this._refreshTimeouts[refreshToken][hash]);
      delete this._refreshTimeouts[refreshToken][hash];
      if (!Object.keys(this._refreshTimeouts[refreshToken]).length) {
        delete this._refreshTimeouts[refreshToken];
      }
    }

    // Create a new abort controller.
    const controller = new AbortController();
    const timeout = setTimeout(() => {
      controller.abort();
    }, (this._config.refreshCachedTokensRequestTimeout || 30) * 1000);
    const request = {
      controller,
      timeout,
      promise: (async () => {
        try {
          // FIXME: This should not need to be cast through any. See:
          // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/35636
          const refreshResponse = await fetch(this._config.authxUrl, {
            method: "POST",
            signal: controller.signal,
            headers: {
              "Content-Type": "application/json"
            },
github faastjs / faast.js / src / google / google-queue.ts View on Github external
export async function receiveMessages(
    pubsub: PubSubApi.Pubsub,
    subscription: string,
    metrics: GoogleMetrics,
    cancel: Promise
): Promise {
    // Does higher message batching lead to better throughput? 10 is the max that AWS SQS allows.
    const maxMessages = 10;
    const source = new AbortController();
    const request = pubsub.projects.subscriptions.pull(
        {
            subscription,
            requestBody: { returnImmediately: false, maxMessages }
        },
        { signal: source.signal }
    );

    const response = await Promise.race([request, cancel]);
    if (!response) {
        source.abort();
        return { Messages: [] };
    }

    metrics.outboundBytes += computeHttpResponseBytes(response.headers);
    metrics.pubSubBytes +=
github Azure / azure-sdk-for-js / test / functional / client.spec.ts View on Github external
it("should throw exception if passed an already aborted signal", async function() {
      const client = new CosmosClient({ endpoint, key: masterKey });
      try {
        const controller = new AbortController();
        const signal = controller.signal;
        controller.abort();
        await client.getDatabaseAccount({ abortSignal: signal });
        assert.fail("Must throw when trying to connect to database");
      } catch (err) {
        assert.equal(err.name, "AbortError", "client should throw exception");
      }
    });
    it("should abort a query", async function() {
github nomiclabs / buidler / packages / buidler-core / src / internal / cli / analytics.ts View on Github external
private _sendHit(hit: RawAnalytics): [AbortAnalytics, Promise] {
    log(`Sending hit for ${hit.dp}`);

    const controller = new AbortController();

    const abortAnalytics = () => {
      log(`Aborting hit for ${JSON.stringify(hit.dp)}`);

      controller.abort();
    };

    const hitPayload = qs.stringify(hit);

    log(`Hit payload: ${JSON.stringify(hit)}`);

    const hitPromise = fetch(googleAnalyticsUrl, {
      body: hitPayload,
      method: "POST",
      signal: controller.signal
    })
github stoplightio / spectral / src / fs / reader.ts View on Github external
export async function readFile(name: string, opts: IReadOptions): Promise {
  if (isURL(name)) {
    let response;
    let timeout: NodeJS.Timeout | number | null = null;
    try {
      if (opts.timeout) {
        const controller = new AbortController();
        timeout = setTimeout(() => {
          controller.abort();
        }, opts.timeout);
        response = await request(name, { signal: controller.signal });
      } else {
        response = await request(name);
      }

      if (!response.ok) throw new Error(response.statusText);
      return await response.text();
    } catch (ex) {
      if (ex.name === 'AbortError') {
        throw new Error('Timeout');
      } else {
        throw ex;
      }
github coralproject / talk / src / core / server / services / fetch / abortAfter.ts View on Github external
function abortAfter(ms: number) {
  const controller = new AbortController();
  const timeout = setTimeout(() => {
    controller.abort();
  }, ms);

  return { controller, timeout };
}
github TinkoffCreditSystems / tinkoff-request / packages / plugin-protocol-http / src / http.ts View on Github external
formHeaders = body.getHeaders && body.getHeaders();
            } else {
                const contentType = propOr(type, type, REQUEST_TYPES);
                formHeaders = contentType ? { 'Content-type': contentType } : {};

                if (!noBody) {
                    body = serialize(type, payload);
                }
            }

            let timer;
            let signal;

            if (AbortController) {
                const controller = new AbortController();
                signal = controller.signal;

                const abort = (abortOptions?) => {
                    if (ended) {
                        return;
                    }

                    ended = true;
                    controller.abort();

                    next({
                        status: Status.ERROR,
                        error: abortOptions || {},
                    });
                };
github vadimdemedes / draqula / src / useQuery.ts View on Github external
useEffect(() => {
		unstable_batchedUpdates(() => {
			setIsLoading(cachedData === undefined);
			setError(undefined);
			setData(cachedData);
		});

		const abortController = new AbortController();
		fetch({signal: abortController.signal});

		return () => abortController.abort();
	}, [fetch]);

abort-controller

An implementation of WHATWG AbortController interface.

MIT
Latest version published 6 years ago

Package Health Score

67 / 100
Full package analysis

Popular abort-controller functions