npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@riim/attempt

v1.2.1

Published

## Installation

Downloads

13

Readme

Attempt

Installation

npm install @riim/attempt --save

Example

import { attempt } from '@riim/attempt';
import { duration } from '@riim/duration';

await attempt(
	() => client.getAuth(),
	{
		maxRetries: 10,
		timeout: duration.s10,
		timeoutAfterError: duration.s1,
		onError: (err) => {
			console.error('Error', err.message);
		},
		onTimeout: () => {
			console.error('Timeout');
		},
		onRetry: (err, leftRetries) => {
			console.warn('!!! RETRY', leftRetries);
		}
	}
);

Options

  • maxRetries - максимальное количество повторов. При этом первая попытка повтором не является, то есть если указано 2, то может быть до 3-х попыток из которых 2 будут повторами. По умолчанию - 0.
  • timeout - Ограничение по времени попытки в миллисекундах. Можно установить в 0 - нет ограничения. По умолчанию - 0.
  • timeoutAfterError - Дополнительная задержка перед повтором после ошибки. Дополнительной задержки нет если повтор происходит из-за прерывания попытки по таймауту. Можно установить в 0. По умолчанию - 0.
  • onError - Обработчик ошибки. Первый аргумент - ошибка, второй - номер повтора. При первом срабатывании номер повтора будет 0 (первая попытка - не повтор). Может возвращать число миллисекунд до повтора переопределяя timeoutAfterError. Таким образом можно гибко управлять стратегией изменения timeoutAfterError:
import { attempt } from '@riim/attempt';
import { duration } from '@riim/duration';

await attempt(
	() => client.getAuth(),
	{
		onError: (err, retryNumber) => {
			console.error('Error', err.message);

			return retryNumber * duration.s5;
		}
	}
);

В примере первый повтор произойдёт мгновенно, так как retryNumber при первом срабатывании onError будет 0, второй повтор произойдёт с задержкой в 5 секунд и дальше задержка будет каждый раз увеличиваться на 5 секунд. Не срабатывает если попытка прервана по таймауту. По умолчанию - null.

  • onTimeout - Обработчик прерывания попытки по таймауту. По умолчанию - null.
  • onRetry - Запускается непосредственно перед повтором (то есть после дополнительной задержки (если она есть)). Первый аргумент - ошибка предыдущей попытки (в том числе AttemptTimeoutError, если попытка прервана по таймауту), второй - количество оставшихся попыток. По умолчанию - null.

Configuration

Используемые по умолчанию значения можно изменить:

import { configure } from '@riim/attempt';

configure({
	maxRetries: 2,
	timeout: 10000,
	timeoutAfterError: 1000,
	discardTimeoutedAttempts: true,
	onAttempt: null,
	onError: null,
	onTimeout: null,
	onRetry: null
});