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

@mtg-tracker/common

v1.0.32

Published

Shared utility library for the MTG Tracker microservices. This package provides common errors, middleware, logging utilities, and database migration tools used across all services.

Readme

@mtg-tracker/common

Shared utility library for the MTG Tracker microservices. This package provides common errors, middleware, logging utilities, and database migration tools used across all services.

Installation

npm install @mtg-tracker/common

Exports

Functions

runMigrations(pool, migrationsDir, service)

Automatically runs SQL migrations for a service. Creates a service-specific migrations tracking table and executes all SQL files in the migrations directory that haven't been run yet.

Parameters:

  • pool (mysql.Pool) - MySQL2 connection pool
  • migrationsDir (string) - Absolute path to the migrations directory
  • service (string) - Service name for tracking migrations

Example:

import { runMigrations } from '@mtg-tracker/common';
import pool from './database';

await runMigrations(pool, path.join(__dirname, 'migrations'), 'auth');

Error Classes

All error classes extend CustomError and provide consistent error serialization across services.

BadRequestError

HTTP 400 error for invalid request data.

CustomError (abstract)

Base class for all custom errors. Provides:

  • statusCode property
  • serializeErrors() method for consistent error formatting

DatabaseConnectionError

HTTP 500 error for database connection failures.

NotAuthorizedError

HTTP 401 error for unauthorized access attempts.

NotFoundError

HTTP 404 error for missing resources.

RequestValidationError

HTTP 400 error for request validation failures. Integrates with express-validator.

Middleware

currentUser

Extracts and verifies JWT from session, attaches user payload to req.currentUser.

User Payload:

{
  id: number;
  email: string;
  username: string;
  role: 'user' | 'admin';
}

Example:

import { currentUser } from '@mtg-tracker/common';

app.use(currentUser);

requireAuth

Ensures user is authenticated. Throws NotAuthorizedError if req.currentUser is not set.

Example:

import { requireAuth } from '@mtg-tracker/common';

router.get('/protected', requireAuth, (req, res) => {
  // User is guaranteed to be authenticated
});

requireAdmin

Ensures user is authenticated AND has admin role. Throws NotAuthorizedError if user is not authenticated or not an admin.

Example:

import { requireAdmin } from '@mtg-tracker/common';

router.delete('/admin/users/:id', requireAdmin, (req, res) => {
  // User is guaranteed to be an admin
});

validateRequest

Validates request using express-validator results. Throws RequestValidationError if validation fails.

Example:

import { body } from 'express-validator';
import { validateRequest } from '@mtg-tracker/common';

router.post(
  '/users',
  [
    body('email').isEmail(),
    body('password').isLength({ min: 6 })
  ],
  validateRequest,
  (req, res) => {
    // Request is validated
  }
);

errorHandler

Global error handler middleware. Catches all errors and returns consistent JSON responses.

Example:

import { errorHandler } from '@mtg-tracker/common';

// Add as last middleware
app.use(errorHandler);

Logging

ServiceLogger

Pino-based logger with custom log levels and pretty printing in development.

Features:

  • Custom log levels: trace, debug, log, info, warn, error, fatal
  • Color-coded output in development
  • JSON output in production (for Loki/Grafana)
  • Service name prefix on all logs

Example:

import { ServiceLogger } from '@mtg-tracker/common';

const logger = new ServiceLogger('auth');

logger.log('Server starting...');
logger.info('User created', { userId: 123 });
logger.error('Database error', error);

Usage Pattern

Typical service setup:

import express from 'express';
import { 
  currentUser, 
  errorHandler, 
  requireAuth,
  ServiceLogger,
  runMigrations 
} from '@mtg-tracker/common';

const app = express();
const logger = new ServiceLogger('my-service');

// Middleware
app.use(express.json());
app.use(currentUser);

// Routes
app.get('/api/protected', requireAuth, (req, res) => {
  res.json({ user: req.currentUser });
});

// Error handling (must be last)
app.use(errorHandler);

// Database migrations
await runMigrations(pool, path.join(__dirname, 'migrations'), 'my-service');

// Start server
app.listen(3000, () => {
  logger.log('Service started on port 3000');
});

Dependencies

  • express - Web framework
  • jsonwebtoken - JWT verification
  • mysql2 - MySQL database driver
  • pino - Logging library
  • pino-pretty - Pretty log formatter for development
  • express-validator - Request validation

Environment Variables

  • JWT_KEY - Secret key for JWT verification (required)
  • LOG_LEVEL - Pino log level (default: 'trace')
  • NODE_ENV - Set to 'production' for JSON logging