rxjs/operators#timeout TypeScript Examples

The following examples show how to use rxjs/operators#timeout. 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: coin-gecko.service.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
public getUSDPrices(tokenAddresses: string[]): Observable<UsdPrice> {

        const ethAddr = environment.ETH_ADDRESS.toLowerCase();
        const ethIndex = tokenAddresses.indexOf(ethAddr);
        if (ethIndex === -1) {
            const url = this.endpoint + `/simple/token_price/ethereum?contract_addresses=${ tokenAddresses.join(',') }&vs_currencies=usd`;
            return this.httpClient.get<UsdPrice>(url).pipe(
                timeout(1000)
            );
        }

        if (tokenAddresses.length === 1) {
            return this.getEthUsdPrice();
        }

        const _tokenAddresses = tokenAddresses.filter((_, i) => i !== ethIndex);
        const url = this.endpoint + `/simple/token_price/ethereum?contract_addresses=${ _tokenAddresses.join(',') }&vs_currencies=usd`;
        const tokensReq$ = this.httpClient.get<UsdPrice>(url).pipe(
            timeout(1000)
        );
        const ethReq$ = this.getEthUsdPrice();
        return combineLatest([tokensReq$, ethReq$]).pipe(
            map(([tokensPrices, ethPrice]) => {
                tokensPrices[ethAddr] = ethPrice[ethAddr];
                return tokensPrices;
            })
        );
    }
Example #2
Source File: home.page.ts    From blog2020 with MIT License 6 votes vote down vote up
async unregister(): Promise<void> {
    await PushNotifications.register();
    const {token} = await FCM.getToken();
    const formData = new FormData();
    formData.append('token', token);
    this.http.post(`${environment.serverURL}/unregister`, formData)
      .pipe(timeout(10000))
      .subscribe(
        {
          next: () => localStorage.setItem('allowPersonal', JSON.stringify(this.allowPersonal)),
          error: () => this.allowPersonal = !this.allowPersonal
        }
      );
  }
Example #3
Source File: home.page.ts    From blog2020 with MIT License 6 votes vote down vote up
async register(): Promise<void> {
    await PushNotifications.register();
    const {token} = await FCM.getToken();
    const formData = new FormData();
    formData.append('token', token);
    this.http.post(`${environment.serverURL}/register`, formData)
      .pipe(timeout(10000))
      .subscribe(
        {
          next: () => localStorage.setItem('allowPersonal', JSON.stringify(this.allowPersonal)),
          error: () => this.allowPersonal = !this.allowPersonal
        }
      );
  }
Example #4
Source File: login.page.ts    From capture-lite with GNU General Public License v3.0 6 votes vote down vote up
onSubmit() {
    this.showResendEmailButton = false;

    const timeoutDue = 20000;
    const action$ = this.diaBackendAuthService
      .login$(this.model.email, this.model.password)
      .pipe(
        timeout(timeoutDue),
        catchError((err: unknown) => this.handleLoginError$(err)),
        tap(_ => (this.onboardingService.isNewLogin = true))
      );

    return this.blockingActionService
      .run$(action$, {
        message: this.translocoService.translate('message.pleaseWait'),
      })
      .pipe(
        concatMapTo(
          defer(() => this.router.navigate(['home'], { replaceUrl: true }))
        ),
        untilDestroyed(this)
      )
      .subscribe();
  }
Example #5
Source File: server-info.component.ts    From models-web-app with Apache License 2.0 6 votes vote down vote up
ngOnInit() {
    this.route.params.subscribe(params => {
      console.log($localize`Using namespace: ${params.namespace}`);
      this.ns.updateSelectedNamespace(params.namespace);

      this.serverName = params.name;
      this.namespace = params.namespace;

      this.pollingSub = this.poller.start().subscribe(() => {
        this.getBackendObjects();
      });
    });

    // don't show a METRICS tab if Grafana is not exposed
    console.log($localize`Checking if Grafana endpoint is exposed`);
    const grafanaApi = environment.grafanaPrefix + '/api/search';

    this.http
      .get(grafanaApi)
      .pipe(timeout(1000))
      .subscribe({
        next: resp => {
          if (!Array.isArray(resp)) {
            console.log(
              $localize`Response from the Grafana endpoint was not as expected.`,
            );
            this.grafanaFound = false;
            return;
          }

          console.log($localize`Grafana endpoint detected. Will expose a metrics tab.`);
          this.grafanaFound = true;
        },
        error: () => {
          console.log($localize`Could not detect a Grafana endpoint..`);
          this.grafanaFound = false;
        },
      });
  }
Example #6
Source File: location.service.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
@Cacheable({
    cacheBusterObserver: currentLocationCacheBuster$,
    maxAge: 10 * 60 * 1000, // 10 minutes
  })
  getCurrentLocation(config: { enableHighAccuracy: boolean } = { enableHighAccuracy: false }): Observable<Position> {
    return from(
      Geolocation.getCurrentPosition({
        timeout: 5000,
        enableHighAccuracy: config.enableHighAccuracy,
      })
    ).pipe(
      this.timeoutWhen(!config.enableHighAccuracy, 5000),
      catchError(() => of(null))
    );
  }
Example #7
Source File: network.service.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public constructor(
    name: string,
    httpClient: HttpClient,
    resetTimeoutMs = AppConfig.defaultHttpResetTimeoutMs,
    httpTimeoutMs = AppConfig.defaultHttpTimeoutMs
  ) {
    this._name = name;
    this._httpClient = httpClient;
    this._defaultTimeoutMs = httpTimeoutMs;
    this._cb = new CircuitBreaker(this.internalAction, {
      timeout: httpTimeoutMs,
      resetTimeout: resetTimeoutMs,
      errorFilter: (err) => {
        // Don't trip the breaker on a 404
        return err.status === 404;
      },
    });
    this._cb.on("open", () => {
      console.log(`${name} circuit breaker open`);
      this._state = "open";
    });
    this._cb.on("close", () => {
      console.log(`${name} circuit breaker close`);
      this._state = "closed";
    });
  }
Example #8
Source File: network.service.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public deleteJson<T>(
    url: URL | string,
    headers: {
      [header: string]: string | string[];
    } = {},
    timeoutMs?: number
  ): Promise<T> {
    const cheaders = headers || {};
    return this.fire<T>(() =>
      firstValueFrom(
        this._httpClient
          .delete<T>(url.toString(), { headers: { ...cheaders } })
          .pipe(first(), timeout(timeoutMs ?? this._defaultTimeoutMs))
      )
    );
  }
Example #9
Source File: network.service.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public postJson<T>(
    url: URL | string,
    body: unknown,
    headers: {
      [header: string]: string | string[];
    } = {},
    timeoutMs?: number
  ): Promise<T> {
    const cheaders = headers || {};
    const ctimeout = timeoutMs ?? this._defaultTimeoutMs;

    return this.fire<T>(() =>
      firstValueFrom(
        this._httpClient.post<T>(url.toString(), body, { headers: { ...cheaders } }).pipe(
          first(),
          // switchMap((r) => mockTimeout<T>(r, 30000)),
          timeout(ctimeout)
        )
      )
    );
  }
Example #10
Source File: network.service.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public getText(url: URL | string, timeoutMs?: number): Promise<string> {
    return this.fire(() =>
      firstValueFrom(
        this._httpClient
          .get(url.toString(), { responseType: "text", headers: { ...CACHE_CONTROL_HEADERS } })
          .pipe(first(), timeout(timeoutMs ?? this._defaultTimeoutMs))
      )
    );
  }
Example #11
Source File: network.service.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
public getJson<T>(
    url: URL | string,
    headers: {
      [header: string]: string | string[];
    } = {},
    timeoutMs?: number
  ): Promise<T> {
    return this.fire(() =>
      firstValueFrom(
        this._httpClient
          .get<T>(url.toString(), { headers: { ...CACHE_CONTROL_HEADERS, ...headers } })
          .pipe(first(), timeout(timeoutMs ?? this._defaultTimeoutMs))
      )
    );
  }
Example #12
Source File: wago-addon-provider.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
private ensureToken(timeoutMs = 10000): Observable<string> {
    if (this._circuitBreaker.isOpen()) {
      throw new Error("[wago] circuit breaker is open");
    }

    return this._apiTokenSrc.pipe(
      timeout(timeoutMs),
      first((token) => token !== ""),
      tap(() => console.log(`[wago] ensureToken`)),
      catchError(() => {
        console.error("[wago] no token received after timeout");
        return of("");
      })
    );
  }
Example #13
Source File: common-rubic-bridge-provider.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
private async loadRubicTokenInfo(): Promise<void> {
    this.httpService
      .get('networks/', {}, this.apiUrl)
      .pipe(
        timeout(3000),
        catchError((e: unknown) => {
          console.error(e);
          this._tokenPairs$.next(List([]));
          return EMPTY;
        })
      )
      .subscribe((response: RubicApiResponse[]) => {
        if (!response) {
          this._tokenPairs$.next(List([]));
          return;
        }
        const bridgeTokenPair = this.getTokenPairs(response);

        this._tokenPairs$.next(List([bridgeTokenPair]));
      });
  }
Example #14
Source File: ledger.service.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
private registerOnLedger(hash: string): Observable<any> {
    const address = 'HEQLOWORLDHELLOWORLDHELLOWORLDHELLOWORLDHELLOWORLDHELLOWORLDHELLOWORLDHELLOWOR99D';
    const seed = 'PUEOTSEITFEVEWCWBTSIZM9NKRGJEIMXTULBACGFRQK9IMGICLBKW9TTEVSDQMGWKBXPVCBMMCXWMNPDX';
    const rawMsg = { hash };
    return from(runTransaction(address, seed, rawMsg))
      .pipe(
        timeout(10000),
        tap(resultHash => console.log(`Hash ${resultHash} registered on ledger`, resultHash)),
        catchError(err => {
          console.log(err);
          return of('');
        })
      );
  }
Example #15
Source File: gas.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Gets ETH gas from different APIs, sorted by priority, in case of errors.
   * @return Observable<number> Average gas price in Gwei.
   */
  @Cacheable({
    maxAge: GasService.requestInterval
  })
  private fetchEthGas(): Observable<number | null> {
    const requestTimeout = 2000;
    return this.httpClient.get('https://gas-price-api.1inch.io/v1.2/1').pipe(
      timeout(requestTimeout),
      map((response: { medium: { maxFeePerGas: string } }) =>
        new BigNumber(response.medium.maxFeePerGas)
          .dividedBy(10 ** 9)
          .dp(0)
          .toNumber()
      ),
      catchError(() =>
        this.httpClient.get('https://ethgasstation.info/api/ethgasAPI.json').pipe(
          timeout(requestTimeout),
          map((response: { average: number }) => response.average / 10)
        )
      ),
      catchError(() => of(null))
    );
  }
Example #16
Source File: coingecko-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Gets price of token in usd from coingecko.
   * @param blockchain Supported by {@link supportedBlockchains} blockchain.
   * @param tokenAddress Address of token to get price for.
   */
  @Cacheable({
    maxAge: 13_000,
    maxCacheCount: 4
  })
  public getCommonTokenPrice(
    blockchain: BlockchainName,
    tokenAddress: string
  ): Observable<number | undefined> {
    if (!this.isSupportedBlockchain(blockchain)) {
      return of(undefined);
    }

    const blockchainId = this.tokenBlockchainId[blockchain];
    return this.httpClient
      .get(`${API_BASE_URL}coins/${blockchainId}/contract/${tokenAddress.toLowerCase()}`)
      .pipe(
        timeout(3_000),
        map((response: { market_data: { current_price: { usd: number } } }) => {
          return response?.market_data?.current_price?.usd;
        }),
        catchError((err: unknown) => {
          console.debug('Coingecko cannot retrieve token price', err);
          return of(undefined);
        })
      );
  }
Example #17
Source File: coingecko-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Gets price of native coin in usd from coingecko.
   * @param blockchain Supported by {@link supportedBlockchains} blockchain.
   */
  @Cacheable({
    maxAge: 13_000,
    maxCacheCount: supportedBlockchains.length
  })
  public getNativeCoinPrice(blockchain: BlockchainName): Observable<number | undefined> {
    if (!this.isSupportedBlockchain(blockchain)) {
      return of(undefined);
    }

    const coingeckoId = this.nativeCoinsCoingeckoIds[blockchain];
    return this.httpClient
      .get(`${API_BASE_URL}simple/price`, {
        params: { ids: coingeckoId, vs_currencies: 'usd' }
      })
      .pipe(
        timeout(3_000),
        map((response: { [key: string]: { usd: string } }) => {
          return +response[coingeckoId].usd;
        }),
        catchError((_err: unknown) => {
          console.debug('Coingecko is not alive');
          return of(undefined);
        })
      );
  }
Example #18
Source File: solana-web3-public.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * HealthCheck Solana RPC node.
   * @param timeoutMs Acceptable node response timeout.
   * @return null if healthcheck is not defined for current blockchain, else is node works status.
   */
  public healthCheck(timeoutMs: number = 4000): Observable<boolean> {
    const request = this.connection.getBalanceAndContext(
      new PublicKey('DVLwQbEaw5txuduQwvfbNP3sXvjawHqaoMuGMKZx15bQ'),
      'confirmed'
    );
    return from(request).pipe(
      timeout(timeoutMs),
      map(result => Boolean(result)),
      catchError((err: unknown) => {
        if ((err as Error)?.name === 'TimeoutError') {
          console.debug(`Solana node healthcheck timeout (${timeoutMs}ms) has occurred.`);
        } else {
          console.debug(`Solana node healthcheck fail: ${err}`);
        }
        return of(false);
      })
    );
  }
Example #19
Source File: 1inch.api.service.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
public getTokens$(): Observable<ISymbol2Token> {

    const url = this.url + '/tokens';

    return this.http.get<{tokens: ISymbol2Token}>(url).pipe(
        timeout(5000),
      delayedRetry(1000)
    ).pipe(
        map((x) => x.tokens)
    );
  }
Example #20
Source File: coin-gecko.service.ts    From gnosis.1inch.exchange with MIT License 6 votes vote down vote up
public getEthUsdPrice(): Observable<UsdPrice> {
        return this.httpClient.get(this.ethUsdPriceEndpoint).pipe(
            timeout(1000),
            map((price) => {
                const priceObj = {};
                const ethAddr = environment.ETH_ADDRESS.toLowerCase();
                priceObj[ethAddr] = price['ethereum'];
                return priceObj;
            })
        );
    }
Example #21
Source File: eth-like-web3-public.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * HealthCheck current rpc node.
   * @param timeoutMs Acceptable node response timeout.
   * @return null If Healthcheck is not defined for current blockchain, else is node works status.
   */
  public healthCheck(timeoutMs: number = 4000): Observable<boolean> {
    const healthcheckData = HEALTHCHECK[this.blockchain.name];
    if (!healthcheckData) {
      return of(null);
    }

    const contract = new this.web3.eth.Contract(
      healthcheckData.contractAbi,
      healthcheckData.contractAddress
    );

    return from(contract.methods.symbol().call()).pipe(
      timeout(timeoutMs),
      map(result => result === healthcheckData.expected),
      catchError((err: unknown) => {
        if ((err as Error)?.name === 'TimeoutError') {
          console.debug(
            `${this.blockchain.label} node healthcheck timeout (${timeoutMs}ms) has occurred.`
          );
        } else {
          console.debug(`${this.blockchain.label} node healthcheck fail: ${err}`);
        }
        return of(false);
      })
    );
  }
Example #22
Source File: websocket-client.ts    From closer-sdk.js with MIT License 6 votes vote down vote up
/**
   * Cold observable
   * @param command Message
   */
  public ask(command: roomCommand.SendMessage | roomCommand.SendCustomMessage): Observable<chatEvents.Received> {
    const ref = this.uuidGenerator.next();
    const newCommand = { ...command, ref };

    return merge(
      of(newCommand).pipe(
        tap((cmd: typeof newCommand) => this.send(cmd)),
        ignoreElements(),
      ),
      this.connection$.pipe(
        filter(chatEvents.Received.isReceived),
        filter(rec => rec.ref === ref),
      ),
      this.connection$.pipe(
        filter(errorEvents.Error.isError),
        filter(rec => rec.ref === ref),
        mergeMap(err => throwError(err, undefined)),
      ),
    ).pipe(
      timeout(this.askTimeoutMs),
      take(1),
    );
  }
Example #23
Source File: gas-refund-api.service.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Fetches past user transactions for gas refund.
   * @return stream that emits once past user refund gas transactions, or empty list if error.
   */
  public getGasRefundTransactions(): Observable<RefundTransaction[]> {
    const endpointUrl = `${GasRefundApiService.baseUrl}/refunds`;
    const walletAddress = this.authService.userAddress;
    return this.httpService.get<RefundTransactionsResponse>(endpointUrl, { walletAddress }).pipe(
      timeout(3000),
      map(response =>
        response.map(item => ({
          ...item,
          network: FROM_BACKEND_BLOCKCHAINS[item.network],
          value: new BigNumber(item.value),
          date: new Date(item.date * 1000)
        }))
      ),
      catchError((e: unknown) => {
        console.error(e);
        return of([]);
      })
    );
  }
Example #24
Source File: api.service.ts    From covid19-people-counter-system with MIT License 5 votes vote down vote up
getDataByCode(code: string):Observable<DataModel[]> {
    return this.http.get<DataModel[]>(`${environment.apiHost}/api/people/${code}`)
      .pipe(
        retry(3), // retry a failed request up to 3 times
        timeout(5000),
        catchError(this.handleError) // then handle the error
      );
  }
Example #25
Source File: platform.ts    From homebridge-esphome-ts with GNU General Public License v3.0 5 votes vote down vote up
protected onHomebridgeDidFinishLaunching(): void {
        let devices: Observable<IEsphomeDeviceConfig> = from(this.config.devices ?? []);
        if (this.config.discover) {
            const excludeConfigDevices: Set<string> = new Set();
            devices = concat(
                discoverDevices(this.config.discoveryTimeout ?? DEFAULT_DISCOVERY_TIMEOUT, this.log).pipe(
                    map((discoveredDevice) => {
                        const configDevice = this.config.devices?.find(({ host }) => host === discoveredDevice.host);
                        let deviceConfig = discoveredDevice;
                        if (configDevice) {
                            excludeConfigDevices.add(configDevice.host);
                            deviceConfig = { ...discoveredDevice, ...configDevice };
                        }

                        return {
                            ...deviceConfig,
                            // Override hostname with ip address when available
                            // to avoid issues with mDNS resolution at OS level
                            host: discoveredDevice.address ?? discoveredDevice.host,
                        };
                    }),
                ),
                // Feed into output remaining devices from config that haven't been discovered
                devices.pipe(filter(({ host }) => !excludeConfigDevices.has(host))),
            );
        }

        this.subscription.add(
            devices
                .pipe(
                    mergeMap((deviceConfig) => {
                        const device = new EspDevice(deviceConfig.host, deviceConfig.password, deviceConfig.port);
                        if (this.config.debug) {
                            this.log('Writing the raw data from your ESP Device to /tmp');
                            writeReadDataToLogFile(deviceConfig.host, device);
                        }
                        device.provideRetryObservable(
                            interval(deviceConfig.retryAfter ?? this.config.retryAfter ?? DEFAULT_RETRY_AFTER).pipe(
                                tap(() => this.log.info(`Trying to reconnect now to device ${deviceConfig.host}`)),
                            ),
                        );
                        return device.discovery$.pipe(
                            filter((value: boolean) => value),
                            take(1),
                            timeout(10 * 1000),
                            tap(() => this.addAccessories(device)),
                            catchError((err) => {
                                if (err.name === 'TimeoutError') {
                                    this.log.warn(
                                        `The device under the host ${deviceConfig.host} could not be reached.`,
                                    );
                                }
                                return of(err);
                            }),
                        );
                    }),
                )
                .subscribe(),
        );
    }
Example #26
Source File: location.service.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
timeoutWhen<T>(cond: boolean, value: number): OperatorFunction<T, T> {
    return (source) => (cond ? source.pipe(timeout(value)) : source);
  }
Example #27
Source File: network.service.ts    From WowUp with GNU General Public License v3.0 5 votes vote down vote up
public getText(url: URL | string, timeoutMs?: number): Promise<string> {
    return firstValueFrom(
      this._httpClient
        .get(url.toString(), { responseType: "text", headers: { ...CACHE_CONTROL_HEADERS } })
        .pipe(first(), timeout(timeoutMs ?? AppConfig.defaultHttpTimeoutMs))
    );
  }
Example #28
Source File: network.service.ts    From WowUp with GNU General Public License v3.0 5 votes vote down vote up
public getJson<T>(url: URL | string, timeoutMs?: number): Promise<T> {
    return firstValueFrom(
      this._httpClient
        .get<T>(url.toString(), { headers: { ...CACHE_CONTROL_HEADERS } })
        .pipe(first(), timeout(timeoutMs ?? AppConfig.defaultHttpTimeoutMs))
    );
  }
Example #29
Source File: tokens.service.ts    From rubic-app with GNU General Public License v3.0 5 votes vote down vote up
/**
   * Get balance for each token in list.
   * @param tokens List of tokens.
   * @return Promise<TokenAmount[]> Tokens with balance.
   */
  private async getTokensWithBalance(tokens: List<TokenAmount>): Promise<TokenAmount[]> {
    try {
      const blockchains = this.walletConnectorService.getBlockchainsBasedOnWallet();

      const tokensWithBlockchain: { [p: string]: TokenAmount[] } = Object.fromEntries(
        blockchains.map(blockchain => [blockchain, []])
      );
      tokens.forEach(tokenAmount =>
        tokensWithBlockchain?.[tokenAmount?.blockchain]?.push(tokenAmount)
      );

      const balances$: Observable<BigNumber[]>[] = blockchains.map(blockchain => {
        const tokensAddresses = tokensWithBlockchain[blockchain].map(el => el.address);

        return from(
          this.publicBlockchainAdapterService[blockchain].getTokensBalances(
            this.userAddress,
            tokensAddresses
          )
        ).pipe(
          timeout(3000),
          catchError(() => [])
        );
      });

      const balancesSettled = await Promise.all(balances$.map(el$ => el$.toPromise()));

      return blockchains
        .map((blockchain, blockchainIndex) => {
          const balances = balancesSettled[blockchainIndex];
          return tokens
            .filter(token => token.blockchain === blockchain)
            .map((token, tokenIndex) => ({
              ...token,
              amount: Web3Pure.fromWei(balances?.[tokenIndex] || 0, token.decimals) || undefined
            }))
            .toArray();
        })
        .filter(t => t !== null)
        .flat();
    } catch (err: unknown) {
      console.debug(err);
    }
  }