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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@groundbrick/db-core

v0.0.1

Published

Core database interfaces and types for the TypeScript microframework

Readme

@groundbrick/db-core

Database abstraction core for the BitBrick microframework

This package provides the backbone for integrating with relational databases (PostgreSQL or MySQL), offering a unified layer for connection handling, querying, transactions, and migrations.


🔧 Key Features

  • Unified interface for database clients
  • Adapter support for PostgreSQL and MySQL (via external factories)
  • Full support for transactions
  • Strongly-typed migration system
  • Configuration validation and health checks
  • Granular error handling by operation type

📦 Installation

npm install @groundbrick/db-core

You will also need to install a specific adapter package such as @groundbrick/db-postgres or @groundbrick/db-mysql.


🚀 Quick Start

import { DatabaseAdapter } from '@groundbrick/db-core';

const adapter = new DatabaseAdapter({
  type: 'postgresql',
  host: 'localhost',
  user: 'admin',
  password: 'secret',
  database: 'mydb',
  port: 5432
});

await adapter.initialize();

const users = await adapter.query('SELECT * FROM users WHERE active = $1', [true]);

await adapter.close();

🔄 Transactions

await adapter.transaction(async (trx) => {
  await trx.query('INSERT INTO logs (event, ts) VALUES ($1, now())', ['create_user']);

  const result = await trx.query<{ id: number }>(
    'INSERT INTO users (email, active) VALUES ($1, $2) RETURNING id',
    ['[email protected]', true]
  );

  const userId = result.rows[0].id;

  await trx.query('INSERT INTO profiles (user_id) VALUES ($1)', [userId]);
});
  • The transaction will automatically commit if successful
  • Any thrown error will rollback the transaction
  • Nested transactions are not natively supported

🧪 Health Check

const status = await adapter.healthCheck();

if (status.status !== 'ok') {
  throw new Error(`Database unavailable: ${status.reason}`);
}

🔍 Pool Info (if supported by the adapter)

const pool = adapter.getClient().getConnectionInfo?.();
if (pool) {
  console.log(`Pool: total=${pool.total}, idle=${pool.idle}, waiting=${pool.waiting}`);
}

⏱ Readiness Check

if (!adapter.isReady()) {
  console.warn('Adapter is not ready yet.');
}

📦 Architecture Overview

🔌 DatabaseAdapter

This class encapsulates adapter selection (PostgreSQL or MySQL), dynamically initializes the correct client, and exposes high-level methods:

  • .initialize() / .close()
  • .query(sql, params)
  • .transaction(cb)
  • .healthCheck()
  • .getClient() (direct access to DatabaseClient)

The dynamic loading logic (e.g., PostgresFactory.getInstance) must be implemented in the actual adapter packages.

🧠 DatabaseClient Interface

Contract that all database adapters must implement:

interface DatabaseClient {
  initialize(): Promise<void>;
  close(): Promise<void>;
  query<T>(sql: string, params?: any[]): Promise<QueryResult<T>>;
  transaction<T>(cb: (trx: DatabaseTransaction) => Promise<T>): Promise<T>;
  healthCheck(): Promise<HealthCheckResult>;
  isReady(): boolean;
}

🔄 DatabaseTransaction

Within a transaction, the callback receives a DatabaseTransaction instance, allowing you to perform isolated queries.


📁 Project Structure

db-core/
├── src/
│   ├── adapters/              # Generic adapter layer
│   ├── base/                  # Reusable base logic (e.g., transactions)
│   ├── custom-types/          # Utility and internal types
│   ├── error-handling/        # Operation-specific error classes
│   ├── interfaces/            # Public contract definitions
│   └── index.ts               # Entry point

🧬 Migrations

The core defines types for managing and recording schema migrations. You can implement your own MigrationManager:

const manager: MigrationManager = getCustomMigrationManager();

const pending = await manager.getPendingMigrations();

for (const migration of pending) {
  try {
    await manager.applyMigration(migration);
    console.log(`Migration ${migration.version} applied`);
  } catch (err) {
    console.error(`Failed to apply migration ${migration.version}:`, err);
    break;
  }
}

Each migration should follow the Migration type contract with up, down, and version fields.


💣 Error Handling

All operations raise specific error classes for easier diagnosis:

  • ConnectionError
  • QueryError
  • MigrationError
  • TransactionError
  • DatabaseError (generic base class)

🧩 Creating a Custom Adapter

Example: PostgreSQL Adapter Factory

export class PostgresFactory {
  static getInstance(config: DatabaseConfig, logger: Logger): DatabaseClient {
    return new PostgresClient(config, logger);
  }
}

Inside DatabaseAdapter, you would dynamically import and use this factory depending on the type.


📝 License

MIT — © 200Systems