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

90dc-core

v1.12.27

Published

Shared utilities, models, and middleware for 90 Day Challenge microservices.

Readme

90dc-core

Shared utilities, models, and middleware for 90 Day Challenge microservices.

Version 1.11.0 - NEW Features ✨

This version adds configuration validation and error handling middleware to improve code quality across all services.

What's New

  • Type-safe configuration with Zod validation
  • Consistent error handling across all services
  • Request validation middleware with Zod
  • Comprehensive error classes (404, 400, 401, 403, 500, etc.)
  • Fail-fast validation on startup

Installation

npm install 90dc-core@latest zod

Quick Start

1. Configuration Validation

import { BaseConfigSchema, ConfigValidator } from '90dc-core';
import { z } from 'zod';

// Extend base config with service-specific settings
const ConfigSchema = BaseConfigSchema.extend({
  GOOGLE_CLIENT_ID: z.string().min(1),
  APPLE_TEAM_ID: z.string().min(1),
  MOLLIE_API_KEY: z.string().min(1)
});

// Create validated config (fails fast on startup if invalid)
const config = new ConfigValidator(ConfigSchema);

// Use with type safety
const port = config.get('PORT'); // Type: number
const jwtSecret = config.get('JWT_SECRET'); // Type: string
const googleClientId = config.get('GOOGLE_CLIENT_ID'); // Type: string

2. Error Handling Middleware

import Koa from 'koa';
import { createErrorMiddleware } from '90dc-core';

const app = new Koa();

// Add error middleware FIRST
app.use(createErrorMiddleware({
  exposeErrorDetails: config.isDevelopment()
}));

// Add your routes
app.use(router.routes());

3. Throwing Errors

import {
  NotFoundError,
  ValidationError,
  ForbiddenError,
  AuthenticationError
} from '90dc-core';

class UserController {
  async getUser(ctx: Context) {
    const user = await User.findByPk(ctx.params.id);

    if (!user) {
      throw new NotFoundError('User'); // Returns 404 with consistent format
    }

    ctx.body = { user };
  }

  async createUser(ctx: Context) {
    const existing = await User.findOne({ where: { email } });

    if (existing) {
      throw new ConflictError('Email already registered'); // Returns 409
    }

    // ... create user
  }
}

4. Request Validation

import { validateRequest } from '90dc-core';
import { z } from 'zod';

const CreateUserSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
  firstName: z.string().min(1).max(100)
});

router.post('/users',
  validateRequest({ body: CreateUserSchema }),
  async (ctx) => {
    // ctx.request.body is now validated and typed
    const user = await User.create(ctx.request.body);
    ctx.body = { user };
  }
);

Error Response Format

All errors return consistent JSON:

{
  "success": false,
  "error": {
    "code": "NOT_FOUND",
    "message": "User not found"
  }
}

With details for validation errors:

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": {
      "validationErrors": [
        {
          "path": "email",
          "message": "Invalid email",
          "code": "invalid_string"
        }
      ]
    }
  }
}

Available Error Types

import {
  ValidationError,         // 400 - Invalid data
  AuthenticationError,     // 401 - Not authenticated
  ForbiddenError,          // 403 - No permission
  NotFoundError,           // 404 - Resource not found
  ConflictError,           // 409 - Resource conflict
  UnprocessableEntityError,// 422 - Semantic error
  RateLimitError,          // 429 - Too many requests
  InternalServerError,     // 500 - Server error
  ServiceUnavailableError, // 503 - Service down
  DatabaseError,           // 500 - Database issue
  ExternalAPIError,        // 502 - External API failed
} from '90dc-core';

Common Config Schemas

Reusable schemas for common configurations:

import { CommonSchemas } from '90dc-core';

const ConfigSchema = BaseConfigSchema
  .extend(CommonSchemas.redis.shape)
  .extend(CommonSchemas.jwt.shape)
  .extend(CommonSchemas.googleOAuth.shape);

Available common schemas:

  • CommonSchemas.database - PostgreSQL configuration
  • CommonSchemas.redis - Redis configuration
  • CommonSchemas.jwt - JWT authentication
  • CommonSchemas.googleOAuth - Google OAuth
  • CommonSchemas.appleOAuth - Apple OAuth
  • CommonSchemas.serviceUrls - Inter-service URLs
  • CommonSchemas.featureFlags - Feature flags

Full Documentation

See USAGE_EXAMPLES.md for:

  • Complete usage examples
  • Migration guide from old code
  • Best practices
  • Testing examples
  • All available features

Exports

Configuration

import {
  ConfigValidator,
  BaseConfigSchema,
  CommonSchemas,
  createConfig,
  ConfigurationError
} from '90dc-core';

Errors

import {
  AppError,
  ValidationError,
  AuthenticationError,
  ForbiddenError,
  NotFoundError,
  ConflictError,
  UnprocessableEntityError,
  RateLimitError,
  InternalServerError,
  ServiceUnavailableError,
  DatabaseError,
  ExternalAPIError,
  isAppError,
  isOperationalError,
  toAppError
} from '90dc-core';

Middleware

import {
  createErrorMiddleware,
  validateRequest,
  asyncHandler,
  type ErrorMiddlewareConfig
} from '90dc-core';

Database Models

import {
  PersistedUser,
  Program,
  Workout,
  Exercise,
  Badge,
  // ... many more
} from '90dc-core';

Utilities

import {
  AuthenticationUtil,
  NotificationsUtil,
  NotificationClient
} from '90dc-core';

Migration Steps

  1. Install dependencies:

    npm install 90dc-core@latest zod
  2. Add config validation:

    import { BaseConfigSchema, ConfigValidator } from '90dc-core';
    const config = new ConfigValidator(BaseConfigSchema);
  3. Add error middleware:

    import { createErrorMiddleware } from '90dc-core';
    app.use(createErrorMiddleware());
  4. Replace error handling:

    // Before
    if (!user) {
      ctx.status = 404;
      ctx.body = { message: 'Not found' };
      return;
    }
    
    // After
    import { NotFoundError } from '90dc-core';
    if (!user) {
      throw new NotFoundError('User');
    }
  5. Add request validation:

    import { validateRequest } from '90dc-core';
    router.post('/users',
      validateRequest({ body: CreateUserSchema }),
      handler
    );

See USAGE_EXAMPLES.md for detailed migration guide.


Building & Publishing

# Install dependencies
npm install

# Build
npm run build

# Publish to npm
npm run publish:build

Changelog

See CHANGELOG.md for version history.


License

ISC


Contributing

This is part of the 90 Day Challenge microservices architecture. See the main refactor plan for contribution guidelines.