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 🙏

© 2026 – Pkg Stats / Ryan Hefner

nestjs-retry-service

v1.0.0

Published

A retry service for Node.js with support for jitter in NestJS.

Readme

RetryService

O RetryService é uma classe utilitária para tentativas automáticas de execução de operações com controle de tentativas e atrasos progressivos (backoff) em caso de falha. É útil em cenários onde você precisa executar uma operação que pode falhar intermitentemente (como chamadas de API ou acesso a banco de dados).

Instalação

Para instalar o RetryService no seu projeto NestJS, basta adicionar o arquivo da classe no seu diretório de serviços e injetá-la onde necessário.

Se você ainda não tem o NestJS instalado, siga as instruções na documentação oficial para configurar um novo projeto.

Como usar

1. Instalar Dependências

Certifique-se de que o LoggerService está instalado e configurado no seu projeto. Caso contrário, você pode usar o logger padrão do NestJS.

2. Importar e Injetar o RetryService

Para utilizar o RetryService em qualquer serviço do seu projeto NestJS, faça a injeção dele no construtor da sua classe.

3. Configuração do RetryService

  • O RetryService possui os seguintes parâmetros de configuração:

    • maxRetries (opcional): Número máximo de tentativas. O padrão é 3.
    • retryDelayMs (opcional): Atraso entre as tentativas em milissegundos. O padrão é 1000 ms (1 segundo).
    • jitterFactor (opcional): Fator que adiciona variação ao atraso. O padrão é 0.5, que significa uma variação entre 0 e 50% do valor de retryDelayMs.
  • Esses parâmetros podem ser passados diretamente para o método retryOperation ou podem ser configurados ao criar a instância do RetryService.

4. Exemplo de utilização

import { Injectable, LoggerService } from '@nestjs/common';
import { RetryService } from './retry.service';

@Injectable()
export class MyService {
  constructor(
    private readonly retryService: RetryService,
    private readonly logger: LoggerService,
  ) {}

  async executeWithRetry() {
    try {
      const result = await this.retryService.retryOperation(
        async () => {
          // Simula uma operação que pode falhar
          throw new Error('Operação falhou');
        },
        5, // Tentar 5 vezes
        500, // Atraso de 500ms entre tentativas
        0.2  // Fator de jitter de 20%
      );
      this.logger.log('Operação bem-sucedida:', result);
    } catch (error) {
      this.logger.error('Falha após todas as tentativas:', error.message);
    }
  }
}

5. Tratamento de erros

  • Se todas as tentativas falharem, o RetryService lança um erro com a mensagem:
Failed after attempt #: <número de tentativas>
  • Além disso, ele registra cada falha no logger configurado, facilitando a monitoração de falhas.

6. Métodos disponíveis

  • retryOperation(operation: () => Promise, maxRetries?: number, retryDelayMs?: number, jitterFactor?: number): Promise

  • Parâmetros:

  • operation: Função assíncrona que retorna uma Promise.
  • maxRetries: Número máximo de tentativas (opcional).
  • retryDelayMs: Atraso entre tentativas (opcional).
  • jitterFactor: Fator de jitter para variação do atraso (opcional).
  • Retorna: O resultado da operação quando bem-sucedida.
  • Lança: Um erro se todas as tentativas falharem.

7. Resumo

  • O RetryService facilita a implementação de lógica de retry com backoff exponencial em NestJS, útil para situações em que operações assíncronas podem falhar temporariamente. Ele permite personalizar o comportamento de tentativas e atrasos e fornece uma maneira robusta de lidar com falhas intermitentes.