or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

auth.mdbase-controller.mddecorators.mdindex.mdmiddleware.mdresults.mdserver.md
tile.json

tessl/npm-inversify-express-utils

Express utilities and decorators for building web applications with Inversify dependency injection container

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/inversify-express-utils@6.5.x

To install, run

npx @tessl/cli install tessl/npm-inversify-express-utils@6.5.0

index.mddocs/

Inversify Express Utils

Inversify Express Utils provides a comprehensive set of utilities and decorators for building Express.js applications using the Inversify dependency injection container. It enables a decorator-based approach for defining controllers and routes, with built-in support for parameter binding, middleware integration, and authentication.

Package Information

  • Package Name: inversify-express-utils
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install inversify-express-utils

Core Imports

import { 
  InversifyExpressServer,
  controller,
  httpGet,
  httpPost,
  BaseHttpController,
  requestParam,
  requestBody,
  queryParam
} from "inversify-express-utils";

For CommonJS:

const { 
  InversifyExpressServer,
  controller,
  httpGet,
  httpPost,
  BaseHttpController,
  requestParam,
  requestBody,
  queryParam
} = require("inversify-express-utils");

Basic Usage

import { Container } from "inversify";
import { InversifyExpressServer, controller, httpGet, requestParam, BaseHttpController } from "inversify-express-utils";
import express from "express";

// Create container and bind controllers
const container = new Container();

@controller("/users")
class UserController extends BaseHttpController {
  @httpGet("/:id")
  public getUser(@requestParam("id") userId: string) {
    return this.ok({ id: userId, name: "John Doe" });
  }
}

// Create and configure server
const server = new InversifyExpressServer(container);
server.setConfig((app) => {
  app.use(express.json());
});

const app = server.build();
app.listen(3000);

Architecture

Inversify Express Utils is built around several key components:

  • Server Wrapper: InversifyExpressServer class that integrates Inversify container with Express
  • Decorator System: Method and parameter decorators for defining routes and extracting request data
  • Controller Base Classes: BaseHttpController and BaseMiddleware providing common functionality
  • Action Results: Rich set of result classes for structured HTTP responses
  • HTTP Context: Request-scoped context providing access to container and user information
  • Type System: Full TypeScript integration with comprehensive interfaces and type definitions

Capabilities

Server Configuration

Core server setup and configuration functionality for integrating Inversify container with Express application. Handles route registration, middleware resolution, and HTTP context management.

class InversifyExpressServer {
  constructor(
    container: interfaces.Container,
    customRouter?: Router | null,
    routingConfig?: RoutingConfig | null,
    customApp?: Application | null,
    authProvider?: (new () => AuthProvider) | null,
    forceControllers?: boolean
  );
  
  setConfig(fn: ConfigFunction): this;
  setErrorConfig(fn: ConfigFunction): this;
  build(): Application;
}

interface RoutingConfig {
  rootPath: string;
}

type ConfigFunction = (app: Application) => void;

Server Configuration

Controller Decorators

Decorator-based routing system for defining controllers and HTTP endpoints. Provides method decorators for all HTTP verbs and parameter decorators for request data extraction.

function controller(path: string, ...middleware: Middleware[]): ClassDecorator;

function httpGet(path: string, ...middleware: Middleware[]): MethodDecorator;
function httpPost(path: string, ...middleware: Middleware[]): MethodDecorator;
function httpPut(path: string, ...middleware: Middleware[]): MethodDecorator;
function httpPatch(path: string, ...middleware: Middleware[]): MethodDecorator;
function httpDelete(path: string, ...middleware: Middleware[]): MethodDecorator;
function httpHead(path: string, ...middleware: Middleware[]): MethodDecorator;
function httpOptions(path: string, ...middleware: Middleware[]): MethodDecorator;

function requestParam(paramName?: string): ParameterDecorator;
function queryParam(queryParamName?: string): ParameterDecorator;
function requestBody(): ParameterDecorator;
function requestHeaders(headerName?: string): ParameterDecorator;
function cookies(cookieName?: string): ParameterDecorator;
function request(): ParameterDecorator;
function response(): ParameterDecorator;
function next(): ParameterDecorator;
function principal(): ParameterDecorator;

Controller Decorators

Base Controller

Base controller class providing helper methods for common HTTP responses and access to HTTP context. Includes methods for standard status codes and content negotiation.

class BaseHttpController {
  protected readonly httpContext: HttpContext;
  
  protected created<T>(location: string | URL, content: T): CreatedNegotiatedContentResult<T>;
  protected conflict(): ConflictResult;
  protected ok<T>(content: T): OkNegotiatedContentResult<T>;
  protected ok(): OkResult;
  protected badRequest(): BadRequestResult;
  protected badRequest(message: string): BadRequestErrorMessageResult;
  protected internalServerError(): InternalServerErrorResult;
  protected internalServerError(error: Error): ExceptionResult;
  protected notFound(): NotFoundResult;
  protected redirect(uri: string | URL): RedirectResult;
  protected statusCode(statusCode: number): StatusCodeResult;
  protected json(content: unknown, statusCode?: number): JsonResult;
  protected stream(readableStream: Readable, contentType: string, statusCode?: number): StreamResult;
}

Base Controller

Action Results

Comprehensive set of action result classes for structured HTTP responses. Implements the action result pattern for type-safe response handling with content negotiation support.

interface IHttpActionResult {
  executeAsync(): Promise<HttpResponseMessage>;
}

class HttpResponseMessage {
  content: HttpContent;
  headers: OutgoingHttpHeaders;
  statusCode: number;
}

// Result classes
class OkResult implements IHttpActionResult;
class OkNegotiatedContentResult<T> implements IHttpActionResult;
class BadRequestResult implements IHttpActionResult;
class NotFoundResult implements IHttpActionResult;
class JsonResult implements IHttpActionResult;
class RedirectResult implements IHttpActionResult;

Action Results

Authentication & Authorization

Authentication and authorization system supporting custom auth providers, user principals, and role-based access control. Integrates seamlessly with dependency injection.

interface Principal<T = unknown> {
  details: T;
  isAuthenticated(): Promise<boolean>;
  isInRole(role: string): Promise<boolean>;
  isResourceOwner(resourceId: unknown): Promise<boolean>;
}

interface AuthProvider {
  getUser(req: Request, res: Response, next: NextFunction): Promise<Principal>;
}

interface HttpContext<T = unknown> {
  container: interfaces.Container;
  request: Request;
  response: Response;
  user: Principal<T>;
}

Authentication

Middleware System

Middleware integration system supporting both Express middleware and custom Inversify-based middleware with dependency injection support.

abstract class BaseMiddleware {
  httpContext: HttpContext;
  
  protected bind<T>(serviceIdentifier: interfaces.ServiceIdentifier<T>): interfaces.BindingToSyntax<T>;
  abstract handler(req: Request, res: Response, next: NextFunction): void | Promise<void>;
}

function withMiddleware(...middleware: Middleware[]): ClassDecorator | MethodDecorator;

type Middleware = interfaces.ServiceIdentifier | RequestHandler;

Middleware

HTTP Content Classes

Content classes for structured HTTP response content with proper MIME type handling. Used internally by action results but also available for custom response scenarios.

abstract class HttpContent {
  readonly headers: OutgoingHttpHeaders;
  abstract readAsync(): Promise<unknown>;
}

class JsonContent extends HttpContent {
  constructor(content: unknown);
  readAsync(): Promise<unknown>;
}

class StringContent extends HttpContent {
  constructor(content: string);
  readAsync(): Promise<string>;
}

class StreamContent extends HttpContent {
  constructor(content: Readable, mediaType: string);
  readAsync(): Promise<Readable>;
}

Debug Utilities

Debug and introspection utilities for getting route information and metadata from the application. Useful for development, testing, and runtime inspection.

function getRouteInfo(container: interfaces.Container): RouteInfo[];
function getRawMetadata(container: interfaces.Container): RawMetadata[];

interface RouteInfo {
  controller: string;
  endpoints: RouteDetails[];
}

interface RouteDetails {
  route: string;
  args?: string[];
}

interface RawMetadata {
  controllerMetadata: ControllerMetadata;
  methodMetadata: ControllerMethodMetadata[];
  parameterMetadata: ControllerParameterMetadata;
}

Constants and Types

enum PARAMETER_TYPE {
  REQUEST,
  RESPONSE,
  PARAMS,
  QUERY,
  BODY,
  HEADERS,
  COOKIES,
  NEXT,
  PRINCIPAL
}

enum HTTP_VERBS_ENUM {
  all = 'all',
  connect = 'connect',
  delete = 'delete',
  get = 'get',
  head = 'head',
  options = 'options',
  patch = 'patch',
  post = 'post',
  propfind = 'propfind',
  put = 'put',
  trace = 'trace'
}

const TYPE = {
  AuthProvider: Symbol.for('AuthProvider'),
  Controller: Symbol.for('Controller'),
  HttpContext: Symbol.for('HttpContext')
};

const METADATA_KEY = {
  controller: 'inversify-express-utils:controller',
  controllerMethod: 'inversify-express-utils:controller-method',
  controllerParameter: 'inversify-express-utils:controller-parameter',
  httpContext: 'inversify-express-utils:httpcontext',
  middleware: 'inversify-express-utils:middleware'
};

Utility Functions

Utility functions for working with controller metadata and Inversify container integration.

function getControllersFromContainer(container: interfaces.Container, forceControllers: boolean): Controller[];
function getControllersFromMetadata(): DecoratorTarget[];
function getControllerMetadata(constructor: NewableFunction): ControllerMetadata;
function getControllerMethodMetadata(constructor: NewableFunction): ControllerMethodMetadata[];
function getControllerParameterMetadata(constructor: NewableFunction): ControllerParameterMetadata;
function cleanUpMetadata(): void;
function instanceOfIhttpActionResult(value: unknown): value is IHttpActionResult;