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-metrics

v0.7.1

Published

Generate chart-ready metrics and trends from your TypeORM entities in NestJS. Fluent API, locale/timezone-aware bucketing, PostgreSQL/MySQL/SQLite.

Readme

nestjs-metrics

npm version npm downloads license types CI

Chart-ready metrics and trends from your TypeORM entities in NestJS. A fluent, database-portable API for dashboards and analytics — built on nestjs-metrics-core.

import { MetricsModule, MetricsService } from 'nestjs-metrics/nestjs';

this.metrics
  .query(orderRepo.createQueryBuilder('orders'))
  .sumByMonth('amount', 12)
  .forYear(2026)
  .fillMissingData()
  .trends();
// → { labels: ['January', ...], data: [...] }

Features

  • Fluent API for count, sum, average, max, min over day/week/month/year.
  • Two entry points — nestjs-metrics (engine) and nestjs-metrics/nestjs (NestJS module).
  • Chart-ready output — trends() returns { labels, data } for Chart.js, Recharts, ApexCharts, etc.
  • Multi-dialect SQL — identical queries on PostgreSQL, MySQL/MariaDB and SQLite.
  • Locale & timezone aware — translated labels and DST-correct bucketing.
  • Built-in helpers — fillMissingData, groupData (stacked series), metricsWithVariations, percentage trends.
  • NestJS integration — global MetricsModule.forRoot, per-module forFeature, injectable MetricsService.
  • Repository helpers — metricsFor(repo) and withMetrics(repo).

Installation

npm install nestjs-metrics typeorm   # typeorm only if you use the TypeORM path

Peer dependencies — both optional, install what you actually use:

  • @nestjs/common ^10 || ^11 — only for the nestjs-metrics/nestjs module/service.
  • typeorm ^0.3 — only for the Metrics.query(qb) / metricsFor / withMetrics paths. Nothing in this package imports it at runtime; it is a type-only reference.

nestjs-metrics-core is installed automatically.

Using a non-TypeORM stack (Kysely, Prisma, Drizzle, raw SQL)? Install without typeorm. MetricsService exposes queryExecutor() and fromRows() alongside query(), so you still get the module's configured locale/timezone/cache defaults:

// in a provider
this.metrics.queryExecutor(dataSource, { table: 'orders' }).sumByMonth('amount').trends();
this.metrics.fromRows(rowsYouAlreadyFetched, { dateColumn: 'created_at' }).countByMonth().trends();

If you don't need the NestJS module at all, depend on nestjs-metrics-core directly.

There is no nestjs-metrics/prisma or nestjs-metrics/kysely subpath. The driver adapters live in nextjs-metrics (nextjs-metrics/prisma, /drizzle, /kysely) — despite the name, that package is not Next.js-specific and works in any Node runtime, including NestJS. Each adapter is a thin DataSource builder, so you can equally skip it and pass your own { dialect, execute } to queryExecutor().

Quick start

Register the module globally:

import { Module } from '@nestjs/common';
import { MetricsModule } from 'nestjs-metrics/nestjs';

@Module({
  imports: [
    MetricsModule.forRoot({
      locale: 'pt-BR',
      timezone: 'America/Sao_Paulo',
    }),
  ],
})
export class AppModule {}

Inject the service and build a trend:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MetricsService } from 'nestjs-metrics/nestjs';
import { Order } from './order.entity';

@Injectable()
export class DashboardService {
  constructor(
    private readonly metrics: MetricsService,
    @InjectRepository(Order) private readonly orders: Repository<Order>,
  ) {}

  async monthlyRevenue() {
    return this.metrics
      .query(this.orders.createQueryBuilder('orders'))
      .sumByMonth('amount', 12)
      .forYear(2026)
      .fillMissingData()
      .trends();
  }
}

Common examples

Single metric

const total = await this.metrics
  .query(orderRepo.createQueryBuilder('orders'))
  .sum('amount')
  .metrics();
// → number

Current month only

const thisMonth = await this.metrics
  .query(orderRepo.createQueryBuilder('orders'))
  .countByMonth(1)
  .metrics();

Group by status

const byStatus = await this.metrics
  .query(orderRepo.createQueryBuilder('orders'))
  .count()
  .labelColumn('status')
  .forYear(2026)
  .trends();
// → { labels: ['pending', 'paid', ...], data: [...] }

Stacked series

const stacked = await this.metrics
  .query(orderRepo.createQueryBuilder('orders'))
  .countByMonth('status', 6)
  .groupData(['pending', 'paid', 'cancelled'])
  .fillMissingData()
  .trends();
// → { labels: [...], data: { total: [...], pending: [...], paid: [...], cancelled: [...] } }

Variation vs previous period

import { Period } from 'nestjs-metrics';

const result = await this.metrics
  .query(orderRepo.createQueryBuilder('orders'))
  .sumByYear('amount', 1)
  .forYear(2026)
  .metricsWithVariations(1, Period.YEAR, true);
// → { count: 100000, variation: { type: 'increase', value: '15.5%' } }

Entry points

| Import | For | Optional peer | | --- | --- | --- | | nestjs-metrics | the engine + fluent API | typeorm | | nestjs-metrics/nestjs | the NestJS module + service | @nestjs/common |

MetricsModule.forRoot is global; MetricsModule.forFeature({ locale, timezone }) overrides within a feature module. Precedence: call option > forFeature > forRoot > library default (en / UTC).

Standalone usage

You do not need NestJS to use the engine:

import { Metrics, metricsFor, withMetrics } from 'nestjs-metrics';

await Metrics.query(orderRepo.createQueryBuilder('orders'))
  .count()
  .metrics();

await metricsFor(orderRepo).sumByMonth('amount').trends();

const repo = withMetrics(orderRepo);
await repo.metrics().countByMonth().trends();

The full fluent API is documented in nestjs-metrics-core — including structured query scoping (where / whereIn) and the fromRows() entry point for in-memory row analysis. Both features work transparently through this package (the builder is re-exported unchanged).

Why nestjs-metrics?

| Feature | nestjs-metrics | Raw TypeORM QueryBuilder | laravel-metrics | |---|---|---|---| | NestJS module | Yes | No | No | | Fluent metrics/trends API | Yes | Partial | Yes | | Locale/timezone bucketing | Yes | Manual | Yes | | fillMissingData / groupData | Yes | Manual | Yes | | PostgreSQL / MySQL / SQLite | Yes | Yes* | Yes | | TypeScript-first | Yes | Yes | No (PHP) |

* TypeORM supports all three drivers, but date-bucketing SQL is your responsibility.

Use nestjs-metrics when you want a reusable, tested DSL for dashboard metrics instead of writing and maintaining date-bucketing SQL by hand.

Production tips

  • Set locale and timezone in forRoot once, override with forFeature per module.
  • Use fillMissingData() so charts never collapse missing buckets.
  • Keep labelColumn values low-cardinality; never use user IDs or dynamic URLs as labels.
  • Enable caching with a Redis CacheStore for hot dashboards.
  • Run your test suite against the real dialect you deploy on; date/time SQL is not identical across drivers.

NestJS guide

For a comprehensive walkthrough of all features, queries, filters and usage patterns, see docs/GUIA-NESTJS.md (Portuguese) and the NestJ ReadMe site (English).

License

MIT