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

@grest-ts/db-mysql

v0.0.20

Published

MySQL database utilities for Grest Framework

Readme

Part of the grest-ts framework. Documentation | All packages

@grest-ts/db-mysql

Thin wrapper around mysql2 to make it easier to use within grest-ts. Handles connection pooling, lifecycle management, configuration via @grest-ts/config, and service registration via @grest-ts/locator.

Defining the Config

Database configuration is defined inside GGConfig.define(). Each GGMysqlConfig creates two config keys: a GGResource for host/connection info and a GGSecret for credentials.

// MyConfig.ts
import { GGConfig } from "@grest-ts/config"
import { GGMysqlConfig } from "@grest-ts/db-mysql"

export const MyConfig = GGConfig.define("/my-service/", () => ({
    db: new GGMysqlConfig("main-db"),
    // optionally pass a schema file for testkit cloning
    // db: new GGMysqlConfig("main-db", resolvePath("./schema/init.sql", import.meta.url)),
}))

Providing Config Values

Local development

Use GGConfigStoreLocal with createLocalConfig for type-safe local values:

// config/local.ts
import { createLocalConfig } from "@grest-ts/config"
import { MyConfig } from "../MyConfig"

export default createLocalConfig(MyConfig, {
    db: {
        host: { database: "my_database", host: "localhost", port: 3306 },
        user: { username: "root", password: "root" },
    }
})

Production

Use a production-safe store (e.g. AWS Secrets Manager). The store interface is the same, only the backing implementation changes.

Wiring in Runtime

Create the config locator and database pool inside your runtime's compose() method:

// my-service.ts
import { GGConfigLocator, GGConfigStoreLocal, GGResource, GGSecret } from "@grest-ts/config"
import { MyConfig } from "./MyConfig"
import localConfig from "./config/local"

class MyRuntime extends GGRuntime {
    protected compose(): void {
        // 1. Wire config store
        new GGConfigLocator(MyConfig)
            .add([GGResource, GGSecret], new GGConfigStoreLocal(MyConfig, localConfig))

        // 2. Create database pool (registers with GGLocator, starts/stops with runtime)
        const db = MyConfig.db.newMysqlPool()

        // 3. Use it in your services
        const userService = new UserService(db)
    }
}

The pool automatically:

  • Registers with GGLocator for dependency injection
  • Starts on runtime.start() and tears down on shutdown
  • Watches for config changes and reconnects when host or credentials update

Queries

// SELECT - returns typed rows
const users = await db.query<UserRow[]>("SELECT id, name FROM users WHERE active = ?", [1])

// INSERT/UPDATE/DELETE - returns ResultSetHeader
const result = await db.execute("INSERT INTO users (name) VALUES (?)", ["Alice"])
console.log(result.insertId, result.affectedRows)

Transactions

// Automatic transaction management
const orderId = await db.runInTransaction(async (conn) => {
    const result = await conn.execute("INSERT INTO orders (user_id) VALUES (?)", [userId])
    await conn.execute("INSERT INTO order_items (order_id, product_id) VALUES (?, ?)", [result.insertId, productId])
    return result.insertId
})

// Manual transaction control
const conn = await db.getConnection()
try {
    await conn.beginTransaction()
    await conn.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", [amount, fromId])
    await conn.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", [amount, toId])
    await conn.commit()
} catch (err) {
    await conn.rollback()
    throw err
} finally {
    conn.release()
}

Config Shape Reference

Host config (GGResource):

| Field | Type | Default | Description | |---|---|---|---| | database | string | required | Database name | | host | string? | "localhost" | Server hostname | | port | number? | 3306 | Server port | | connectionLimit | number? | 20 | Max pool connections |

User config (GGSecret):

| Field | Type | Description | |---|---|---| | username | string? | Database username | | password | string? | Database password |

Testkit

The package includes a testkit entrypoint (@grest-ts/db-mysql/testkit) with utilities for schema cloning and test database management.

import { GGTest } from "@grest-ts/testkit"

// Clone database for isolated test - creates a fresh copy per test
GGTest.with(MyConfig.db).clone()

// Clone with seed data
GGTest.with(MyConfig.db).clone("seed.sql")

// Clone with explicit source config (when no defaults are set)
GGTest.with(MyConfig.db).clone({ from: mysqlLocalConfig, seedFiles: ["seed.sql"] })