InversifyJS

repository·main·Indexed 42 days ago

https://github.com/inversify/monorepo

A powerful and lightweight inversion of control (IoC) container for JavaScript and Node.js applications powered by TypeScript. It provides a Dependency Injection (DI) framework that adheres to SOLID principles and supports extensions such as @inversifyjs/plugin-dispose for lifecycle management of singleton services and @inversifyjs/strongly-typed for compile-time type safety of container bindings and injections.

Tokens
105K
Snippets
343
Records
586
Agent score
55%

What's inside InversifyJS

  1. Overview of @inversifyjs/http-open-api

    main

    The @inversifyjs/http-open-api package provides OpenAPI 3.1 integration for InversifyJS HTTP applications. It allows you to automatically generate OpenAPI specifications and interactive Swagger UI documentation from your TypeScript controllers and schemas.

    Key Features:

    • Decorator-based API Documentation: Annotate controllers, methods, and data models using TypeScript decorators.
    • Automatic Schema Generation: Derive OpenAPI schemas from TypeScript classes.
    • Swagger UI Integration: Includes a built-in provider to serve interactive documentation.
    • Type-safe Schema References: Reference schema classes safely within your code.
    • Comprehensive OpenAPI 3.1 Support: Covers operations, request/response bodies, parameters, security, and servers.
    • Framework Agnostic: Compatible with Express, Fastify, Hono, and other supported HTTP frameworks.
  2. Overview of @inversifyjs/http-validation ecosystem

    main

    The @inversifyjs/http-validation package ecosystem provides validation capabilities for InversifyJS HTTP applications. It allows you to validate request data using multiple approaches, ensuring type safety and automatic error handling in your APIs.

    Key Features

    • Multiple Validation Approaches: Supports Ajv (JSON Schema), class-validator (decorator-based), and Standard Schema (Zod, Valibot, ArkType, etc.).
    • Decorator-based Integration: Apply validation rules directly to controller methods and parameters using TypeScript decorators.
    • Type-safe Validation: Combines compile-time type checking with runtime validation.
    • Automatic Error Handling: Includes built-in error filters that transform validation errors into appropriate HTTP responses.
    • Framework Agnostic: Compatible with Express, Fastify, Hono, and other supported HTTP frameworks.
    • Performance: Uses compiled validation pipes for optimal runtime performance.
  3. Overview of the Inversify HTTP Framework

    main

    The Inversify HTTP Framework is a decorator-driven framework for building type-safe HTTP servers using InversifyJS Dependency Injection. It provides a cohesive set of building blocks designed to work across multiple adapters, including Express 4/5, Fastify, and Hono.

    Key features include:

    • Controller-driven routing: Use @Controller(), @Get(), and @Post() to define routes.
    • Type-safe parameter reading: Use parameter decorators to extract request data (body, query, params, headers, cookies) safely.
    • First-class integrations: Built-in support for OpenAPI/Swagger, validation, logging, and authentication.
    • Adapter Agnostic: Most controller code is written once and can run on different runtimes.
  4. What is InversifyJS?

    main

    InversifyJS is a lightweight inversion of control (IoC) container designed for TypeScript and JavaScript applications. It uses class constructors to identify and inject dependencies, helping developers implement robust Object-Oriented (OO) designs such as SOLID principles and Composition over Inheritance.

    Key goals of the project include:

    • Adherence to SOLID principles.
    • Encouragement of best OOP and IoC practices.
    • Minimal runtime overhead.
    • A high-quality development experience.
  5. Use @inversifyjs/config-yaml for YAML configuration

    main
    The @inversifyjs/config-yaml package provides a ConfigSource implementation for @inversifyjs/config that allows you to load and manage application configurations using YAML files. This is useful when you want to externalize your InversifyJS dependency injection configuration into a human-readable YAML format.
  6. Generate TypeScript types from OpenAPI documents

    main

    The @inversifyjs/open-api-2-typescript package converts OpenAPI documents into TypeScript type declarations. It works by collecting components.schemas and operation parameter schemas, then composing them using @inversifyjs/json-schema-2-typescript.

    Naming Conventions

    • Schemas: Uses the schema title as the TypeScript name if present; otherwise, it uses the component key.
    • Operation Parameters: Types for path, query, querystring, header, and cookie parameters are named using the PascalCase operationId (or a combination of HTTP method and path) plus a location suffix:
      • PathParams
      • Query
      • Querystring
      • Headers
      • Cookies
    • Omissions:
      • Locations with no parameters for a specific operation are omitted.
      • Header parameters named Accept, Content-Type, or Authorization (case-insensitive) are ignored per OpenAPI 3.1/3.2 requirements.
    • Root Type: The generated Root type is a union of all collected schemas.

    Special Behaviors

    • Querystring Unwrapping: If an operation has a single querystring parameter, the generated type is the schema of that parameter directly. If there are multiple querystring parameters, they are generated as an object keyed by the parameter names.
    • Reference Resolution: $ref values (including fragment-only refs like #/components/parameters/Page and OpenAPI 3.2 $self) are resolved against the document URI. Refs that do not resolve to a resource within the document are omitted.

    Supported OpenAPI Versions

    • @inversifyjs/open-api-2-typescript/v3Dot1
    • @inversifyjs/open-api-2-typescript/v3Dot2
    import { transformOpenApiToTypeScript } from '@inversifyjs/open-api-2-typescript/v3Dot1';
    
    const typeScript = transformOpenApiToTypeScript({
      components: {
        schemas: {
          User: {
            properties: {
              id: { type: 'string' },
            },
            required: ['id'],
            type: 'object',
          },
        },
      },
      info: { title: 'API', version: '1.0.0' },
      openapi: '3.1.0',
    });
  7. Performance improvements in InversifyJS v7

    main

    InversifyJS v7 (alpha) includes significant performance optimizations. Benchmarks indicate that the library now performs at levels comparable to tsyringe, and in several scenarios (such as getting services in singleton scope for both CJS and ESM), it outperforms tsyringe in terms of latency and throughput.

    Key performance areas include:

    • Getting services in singleton scope.
    • Getting services in transient scope.
    • Getting complex services in both singleton and transient scopes.

    These improvements apply to both CommonJS (CJS) and ECMAScript Module (ESM) environments.

  8. Use @inversifyjs/binding-decorators to streamline container configuration

    main

    The @inversifyjs/binding-decorators package allows you to use decorators to declare and organize dependencies directly on your class definitions. This approach reduces the boilerplate required to manually call container.bind() for every service and keeps your binding logic co-located with the implementation.

    Key Features

    • @provide() decorator: Automatically registers classes into the InversifyJS Container.
    • Named and Tagged Bindings: Supports advanced binding configurations via decorators.
    • Optionality: This package is layered on top of the core InversifyJS container, meaning it is an optional enhancement and does not replace the core functionality.