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

ts-express-generic

v0.0.10

Published

A generic TypeScript controller and service response types for Express

Readme

Express TypeScript Controller Library

npm version License: MIT

A type-safe Express controller library for Node.js with robust type validation and structured service responses.

Features

  • 🛡️ Type-safe request processing (body, params, query, headers, locals)
  • 🚦 Comprehensive HTTP status codes (2xx, 4xx, 5xx) with type-safe mappings
  • 📦 Structured service responses (success/error formats)
  • 🧩 Express middleware compatibility
  • ⚡ Built-in error handling

Installation

npm install express-ts-controller

Quick Start

import express from 'express';
import {
  genericController,
  ServiceResponse,
  HTTPStatusMap
} from 'express-ts-controller';

const app = express();
app.use(express.json());

// Example service function
const userService = async (input: ): Promise<ServiceResponse> => ({
  status: 'OK',
  message: 'User found',
  data: {
    id: input.params.id,
    authUserId: input.locals.userId
  }
});

app.get('/users/:id',
  genericController({
    requestKeys: ['params', 'locals'],
    middlewares: [authMiddleware],
    service: userService
  })
);

app.listen(3000);

Core Concepts

Controller Configuration

type ControllerConfig<T extends TAllowedRequestKeys, R extends TExtractedRequest<T>> = {
  service: ServiceFunction<R, ServiceResponse>;
  requestKeys: T[];
  middlewares: RequestHandler[];
};

Service Responses

Success Response:

{
  status: 'OK' | 'CREATED' | ...,  // TGoodStatus values
  message: string,
  data?: unknown
}

Error Response:

{
  status: 'BAD_REQUEST' | 'INTERNAL_SERVER_ERROR' | ...,  // TBadStatus/TServerStatus values
  message: string,
  error: unknown
}

HTTP Status Codes

Access status codes directly or via helper function:

import { HTTPStatusMap, getHTTPStatus } from 'express-ts-controller';

console.log(HTTPStatusMap.NOT_FOUND);  // 404
console.log(getHTTPStatus('UNAUTHORIZED'));  // 401

API Reference

genericController(config)

Parameters:

| Key | Type | Description | | :---------- | :--------- | :------------------------------------------ | | service | ServiceFunction | Core business logic function | | requestKeys | TAllowedRequestKeys[] | Request parts to extract (e.g., ['body', 'params']) | | middlewares | RequestHandler[] | Express middlewares to apply |

Type Exports

// Request handling
type TAllowedRequestKeys = "body" | "params" | "query" | "headers" | "locals";
type TExtractedRequest<T extends TAllowedRequestKeys> = ...;

// HTTP Status
type TGoodStatus = keyof typeof HTTPGoodStatus;
type TBadStatus = keyof typeof HTTPBadStatus;
type TServerStatus = keyof typeof HTTPServerErrorStatus;

// Service functions
type ServiceFunction<TInput, TResponse> = (input: TInput) => Promise<TResponse>;

Error Handling

The controller automatically catches errors and forwards them to Express error middleware:

// Example error handler
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
  res.status(HTTPStatusMap.INTERNAL_SERVER_ERROR).json({
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Unexpected server error',
    error: error.message
  });
});

Best Practices

  • Validation Middleware: Validate requests before controller handling

  • Type Safety: Always type your service inputs and responses

  • Status Codes: Use appropriate HTTP status codes from HTTPStatusMap

  • Error Formatting: Maintain consistent error responses across services

Contributing

  • Fork the repository

  • Create your feature branch (git checkout -b feature/amazing-feature)

  • Commit your changes (git commit -m 'Add amazing feature')

  • Push to the branch (git push origin feature/amazing-feature)

  • Open a Pull Request

License

Distributed under the MIT License. See LICENSE for more information.