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

@tresdoce-nestjs-toolkit/health

v2.0.13

Published

Tresdoce NestJS Toolkit - Módulo health checks liveness y readiness

Downloads

1,673

Readme

⚠️ Es importante tener en cuenta que este módulo se encuentra implementado en el package @tresdoce-nestjs-toolkit/paas, ya que es una funcionalidad core para el starter.

Este módulo está pensado para ser utilizado en NestJS Starter, o cualquier proyecto que utilice una configuración centralizada, siguiendo la misma arquitectura del starter.

Glosario


📝 Requerimientos básicos

🛠️ Instalar dependencia

npm install -S @tresdoce-nestjs-toolkit/health
yarn add @tresdoce-nestjs-toolkit/health

📦 Dependencias internas

Este paquete requiere los siguientes paquetes del toolkit:

| Paquete | Razón | | ------------------------------------------------ | ---------------------------------------------------------------- | | @tresdoce-nestjs-toolkit/core | Tipos Typings.AppConfig, decoradores base y utilidades comunes | | @tresdoce-nestjs-toolkit/tracing | Decorador @SkipTrace y contexto de OpenTelemetry |

⚙️ Configuración

El módulo utiliza la configuración centralizada para ejecutar los health checks correspondientes a los servicios configurados.

Siguiendo la arquitectura del NestJS Starter, la información agregada en health y services impacta directamente en el endpoint /health/readiness, así como también la presencia de configuraciones de elasticsearch, typeorm, redis y camunda.

//./src/config/configuration.ts
import { getSkipHealthChecks, Typings } from '@tresdoce-nestjs-toolkit/core';
import { registerAs } from '@nestjs/config';

export default registerAs('config', (): Typings.AppConfig => {
  return {
    //...
    health: {
      skipChecks: getSkipHealthChecks(process.env.SKIP_HEALTH_CHECKS),
      storage: {
        path: '/',
        thresholdPercent: 0.9,
      },
      memory: {
        heap: 300 * 1024 * 1024, // 300 MB en bytes
        rss: 300 * 1024 * 1024, // 300 MB en bytes
      },
    },
    services: {
      myApi: {
        url: process.env.MY_API_URL,
      },
      myApiTwo: {
        url: process.env.MY_API_TWO_URL,
        timeout: 5000,
        healthPath: '/health/liveness',
      },
    },
    //...
  };
});

Health

skipChecks: Lista de checks a omitir en el readiness. Si no se requiere omitir ninguno, se recomienda remover la variable y su configuración.

  • Type: String[]
  • Values: storage | memory | elasticsearch | redis | camunda | typeorm
  • Example: elasticsearch,memory

storage: Configuración para el check de disco mediante DiskHealthIndicator.checkStorage().

| Propiedad | Type | Description | | ------------------ | -------- | ---------------------------------------------------------------------------------------- | | path | string | Ruta del sistema de archivos a monitorear (ej: '/' en Linux, 'C:\\' en Windows). | | thresholdPercent | number | Porcentaje máximo de uso de disco permitido, entre 0 y 1. Ej: 0.9 equivale al 90%. |

memory: Configuración para los checks de memoria mediante MemoryHealthIndicator.

| Propiedad | Type | Description | | --------- | -------- | ----------------------------------------------------------------------------- | | heap | number | Límite en bytes para el uso del heap de Node.js (checkHeap). | | rss | number | Límite en bytes para el RSS (Resident Set Size) del proceso (checkRSS). |

Services

timeout: Tiempo máximo de respuesta del servicio en milisegundos.

  • Type: Number
  • Default: 0

healthPath: Endpoint al cual se realiza el ping check del servicio. Si no se especifica, se usa el path por defecto.

  • Type: String
  • Default: /health/liveness

Checks automáticos por configuración

El módulo agrega checks automáticamente al readiness si detecta las siguientes claves en la configuración centralizada:

| Configuración presente | Check agregado | Key de resultado en readiness | | ------------------------- | ------------------------------------------- | ----------------------------- | | config.database.typeorm | Ping a TypeORM con TypeOrmHealthIndicator | typeorm-<type> | | config.redis | Ping a Redis vía microservicio | redis o redis-<name> | | config.elasticsearch | Ping HTTP al nodo de Elasticsearch | elasticsearch | | config.camunda | Ping HTTP a <camunda.baseUrl>/version | camunda |

Cada uno de estos checks puede omitirse individualmente usando health.skipChecks.

👨‍💻 Uso

Importar HealthModule en el módulo principal de la aplicación.

//./src/app.module.ts
import { HealthModule } from '@tresdoce-nestjs-toolkit/health';

@Module({
  imports: [
    //...
    HealthModule,
    //...
  ],
  //...
})
export class AppModule {}

Para visualizar las respuestas de los endpoints, navegar a /health/liveness y /health/readiness.

Liveness

Schema: <http|https>://<server_url><:port>/<app-context>/health/liveness Example: http://localhost:8080/v1/health/liveness

El endpoint de liveness verifica que el proceso de Node.js está en ejecución. No depende de servicios externos.

Response

{
  "status": "up"
}

Readiness

Schema: <http|https>://<server_url><:port>/<app-context>/health/readiness Example: http://localhost:8080/v1/health/readiness

El endpoint de readiness ejecuta todos los health checks configurados. Las claves de cada servicio en services aparecen con el prefijo service- en la respuesta.

Response exitosa

{
  "status": "ok",
  "info": {
    "service-myApi": {
      "status": "up"
    },
    "service-myApiTwo": {
      "status": "up"
    }
  },
  "error": {},
  "details": {
    "service-myApi": {
      "status": "up"
    },
    "service-myApiTwo": {
      "status": "up"
    }
  }
}

Response con error

{
  "status": "error",
  "info": {
    "service-myApi": {
      "status": "up"
    }
  },
  "error": {
    "service-myApiTwo": {
      "status": "down",
      "message": "connect ECONNREFUSED myApiTwo.example.com"
    }
  },
  "details": {
    "service-myApi": {
      "status": "up"
    },
    "service-myApiTwo": {
      "status": "down",
      "message": "connect ECONNREFUSED myApiTwo.example.com"
    }
  }
}

Response con checks adicionales (storage, memory, typeorm)

{
  "status": "ok",
  "info": {
    "storage": {
      "status": "up"
    },
    "memory_heap": {
      "status": "up"
    },
    "memory_rss": {
      "status": "up"
    },
    "typeorm-postgres": {
      "status": "up"
    },
    "service-myApi": {
      "status": "up"
    }
  },
  "error": {},
  "details": {
    "storage": {
      "status": "up"
    },
    "memory_heap": {
      "status": "up"
    },
    "memory_rss": {
      "status": "up"
    },
    "typeorm-postgres": {
      "status": "up"
    },
    "service-myApi": {
      "status": "up"
    }
  }
}

Excluir rutas de salud en middlewares

Para evitar que los middlewares globales (autenticación, logging, etc.) intercepten las rutas de health, se puede usar el array controllersExcludes exportado por el módulo:

//./src/app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { HealthModule, controllersExcludes } from '@tresdoce-nestjs-toolkit/health';
import { SomeMiddleware } from './some.middleware';

@Module({
  imports: [HealthModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(SomeMiddleware)
      .exclude(...controllersExcludes)
      .forRoutes('*');
  }
}

El array controllersExcludes contiene las rutas GET /health/liveness y GET /health/readiness.

📋 API Reference

Constantes exportadas

| Constante | Valor | Descripción | | ------------------------------- | -------------------- | ------------------------------------------------------------------------------------------ | | DEFAULT_SERVICE_LIVENESS_PATH | '/health/liveness' | Path por defecto usado en el ping check de servicios cuando no se especifica healthPath. | | controllersExcludes | RouteInfo[] | Array con las rutas de liveness y readiness, útil para excluirlas de middlewares globales. |

HealthModule

Módulo global que registra los controllers de liveness y readiness, e inyecta la configuración centralizada mediante el token CONFIG_OPTIONS.

Endpoints

| Método | Ruta | Descripción | | ------ | ------------------- | --------------------------------------------------- | | GET | /health/liveness | Retorna { status: 'up' } si el proceso está vivo. | | GET | /health/readiness | Ejecuta todos los health checks configurados. |

📄 Changelog

Todos los cambios notables de este paquete se documentarán en el archivo Changelog.