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

typeorm-fastify-plugin

v4.0.0

Published

An updated fastify-typeorm-plugin for Fastify and Typeorm

Downloads

6,465

Readme

typeorm-fastify-plugin

GitHub Workflow Status npm node

A Fastify plugin that connects, organizes, and decorates your TypeORM DataSource instances. Includes health checks, connection retry, transaction helpers, and automatic Pino logging.

Install

npm install typeorm-fastify-plugin typeorm fastify

typeorm and fastify are peer dependencies — install the versions your project needs. You also need the driver for your database (e.g. pg, mysql2, better-sqlite3).

Quick Start

import Fastify from 'fastify';
import plugin from 'typeorm-fastify-plugin';

const fastify = Fastify({ logger: true });

fastify.register(plugin, {
	type: 'postgres',
	host: 'localhost',
	port: 5432,
	username: 'app',
	password: 'secret',
	database: 'mydb',
	entities: [User, Product],
	synchronize: false
});

await fastify.ready();

const users = await fastify.orm.getRepository(User).find();

The Fastify instance is decorated with orm — a fully initialized TypeORM DataSource available everywhere in your app.

Pre-built DataSource

import { DataSource } from 'typeorm';

const connection = new DataSource({
	type: 'postgres',
	host: 'localhost',
	database: 'mydb',
	entities: [User]
});

fastify.register(plugin, { connection });

Multiple Namespaces

Register multiple databases using the namespace option:

fastify.register(plugin, {
	namespace: 'primary',
	type: 'postgres',
	host: 'localhost',
	database: 'main_db'
});

fastify.register(plugin, {
	namespace: 'analytics',
	type: 'postgres',
	host: 'localhost',
	database: 'analytics_db'
});

await fastify.ready();

fastify.orm['primary'].getRepository(User);
fastify.orm['analytics'].getRepository(Event);

Health Check

import { healthCheck } from 'typeorm-fastify-plugin';

fastify.get('/health/db', async () => {
	const healthy = await healthCheck(fastify.orm);
	if (!healthy) throw { statusCode: 503, message: 'database unavailable' };
	return { status: 'ok' };
});

Runs a driver-aware ping (SELECT 1, SELECT 1 FROM DUAL for Oracle, etc.). Returns false for uninitialized connections or query failures.

Transactions

import { transact } from 'typeorm-fastify-plugin';

const userId = await transact(fastify.orm, async (manager) => {
	const user = manager.getRepository(User).create({ name: 'Alice' });
	const saved = await manager.getRepository(User).save(user);
	return saved.id;
});

Wraps the callback in BEGIN / COMMIT with automatic ROLLBACK on error.

Connection Retry

fastify.register(plugin, {
	type: 'postgres',
	host: 'localhost',
	database: 'mydb',
	retries: 3,
	retryDelay: 1000 // ms, doubles each attempt (exponential backoff)
});

If all attempts fail, throws a TypeOrmPluginError with sanitized connection details (no password).

Logging

When Fastify logging is enabled and no custom logger is provided, the plugin automatically bridges TypeORM logs through Pino via PinoTypeormLogger.

const fastify = Fastify({ logger: true });

fastify.register(plugin, {
	type: 'postgres',
	host: 'localhost',
	database: 'mydb',
	logging: ['query', 'error']
});

You can also use it directly:

import { PinoTypeormLogger } from 'typeorm-fastify-plugin';

const ds = new DataSource({
	type: 'postgres',
	logging: ['query', 'error'],
	logger: new PinoTypeormLogger(fastify.log, ['query', 'error'])
});

To use a different logger, pass any TypeORM-compatible logger:

fastify.register(plugin, {
	type: 'postgres',
	host: 'localhost',
	database: 'mydb',
	logger: 'advanced-console'
});

API

Plugin Options

| Option | Type | Default | Description | | ------------ | ------------------- | ------- | -------------------------------------------------- | | connection | DataSource | — | Pre-built DataSource instance | | namespace | string | — | Register under a namespace key | | retries | number | 0 | Additional connection attempts after first failure | | retryDelay | number | 1000 | Base delay in ms (doubles each retry) | | ...rest | DataSourceOptions | — | Passed directly to new DataSource() |

Exports

| Export | Description | | ----------------------- | ------------------------------------------------------------ | | default | Fastify plugin function | | healthCheck(ds) | Returns Promise<boolean> — driver-aware connectivity check | | transact(ds, fn) | Runs fn inside a transaction, returns its result | | TypeOrmPluginError | Error class with .connectionDetails and .cause | | PinoTypeormLogger | TypeORM logger that routes through Pino | | TypeOrmNamespaceStore | Type for namespace mode ({ [key]: DataSource }) | | DatabaseConfigOptions | Type for plugin options |

License

MIT