### Marking Code Example Start Source: https://github.com/inversify/monorepo/blob/main/packages/docs/tools/inversify-http-open-api-code-examples/README.md Use the `// Begin-example` comment to indicate the start of a code example block that should be processed. ```javascript // Begin-example ``` -------------------------------- ### Complete Hono Application Setup with Better Auth Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/ecosystem/better-auth/api/container-modules.mdx This example demonstrates a full setup of a Hono application integrated with Better Auth using its container module and `fromOptions()` factory. ```typescript import { Container } from "inversify"; import { BetterAuthHonoContainerModule } from "@inversifyjs/http-better-auth/hono"; import { BetterAuth } from "@inversifyjs/http-better-auth"; import { Hono } from "hono"; // Create a new Hono application const app = new Hono(); // Create a new InversifyJS container const container = new Container(); // Load the BetterAuthHonoContainerModule container.load( BetterAuthHonoContainerModule.fromOptions( "/api/auth", new BetterAuth({}) ) ); // Get the BetterAuth instance from the container const betterAuth = container.get(betterAuthServiceIdentifier); // Use BetterAuth with Hono app.use(betterAuth.hono()); // Export the Hono app export default app; ``` -------------------------------- ### Server Setup After Migration (@inversifyjs/http-express) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/faq/migrating-from-inversify-express-utils.mdx Example of server setup using the newer @inversifyjs/http-express package. Body parsing is now handled via adapter options. ```typescript import { Container } from 'inversify'; import { InversifyHttpServer, InversifyHttpServerSettings } from '@inversifyjs/http-core'; import './controllers/foo_controller'; const container = new Container(); container.bind('FooService').to(FooService); const settings: InversifyHttpServerSettings = { useJson: true, useUrlEncoded: true, }; const server = new InversifyHttpServer(container, settings); server.setErrorConfig((app) => { app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); }); const app = await server.build(); app.listen(3000); ``` -------------------------------- ### Server Setup Before Migration (inversify-express-utils) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/faq/migrating-from-inversify-express-utils.mdx Example of server setup using the older inversify-express-utils package. Note the use of setConfig for body parsing. ```typescript import * as bodyParser from 'body-parser'; import { Container } from 'inversify'; import { InversifyExpressServer } from 'inversify-express-utils'; import './controllers/foo_controller'; const container = new Container(); container.bind('FooService').to(FooService); const server = new InversifyExpressServer(container); server.setConfig((app) => { app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); }); server.setErrorConfig((app) => { app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); }); }); const app = server.build(); app.listen(3000); ``` -------------------------------- ### Build and Generate Examples Source: https://github.com/inversify/monorepo/blob/main/packages/docs/tools/AGENTS.md Build the project and generate documentation examples. This command compiles the code and produces the example output files. ```bash pnpm run build ``` ```bash pnpm run generate:examples ``` -------------------------------- ### API Introduction and Validation Setup Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/blog/2026-04-04-openapi-body-validation/index.mdx This example demonstrates the basic setup for API validation using OpenAPI specifications. It shows how to use decorators like @OasRequestBody and @ValidatedBody, and how OpenApiValidationPipe integrates with the OpenAPI document for runtime validation. ```typescript import apiIntroductionSource from '@inversifyjs/validation-code-examples/generated/examples/v1/openApiValidation/apiIntroduction.ts.txt'; import CodeBlock from '@theme/CodeBlock'; {apiIntroductionSource} ``` -------------------------------- ### Add Code Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/tools/binding-decorators-code-examples/README.md Follow these steps to add a new code example. Ensure each example has integration tests and uses specific comments for control. ```bash // Begin-example // Exclude-from-example // Is-inversify-import-example // End-example // Shift-line-spaces-2 ``` -------------------------------- ### Basic Usage Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-uwebsockets-http-adapter.mdx Demonstrates the basic setup and usage of the InversifyUwebSocketsHttpAdapter with a simple InversifyJS application. ```typescript import "reflect-metadata"; import { Container, injectable, inject, } from "inversify"; import { controller, httpGet, InversifyHttpServer, InversifyHttpServerSettings, } from "inversify-express-utils"; import { InversifyUwebSocketsHttpAdapter, UwebSocketsHttpAdapterOptions, } from "@inversifyjs/http-uwebsockets"; import { App, HttpRequest, HttpResponse, } from "uWebSockets.js"; // --- Controllers --- @injectable() @controller("/users") class UsersController { @httpGet("/:id") getById(@inject("UserId") id: string): string { return `User with id ${id} not found`; } } // --- App --- async function bootstrap() { const container = new Container(); container.bind("UserId").toConstant("123"); container.bind(UsersController).toSelf(); const httpAdapter = new InversifyUwebSocketsHttpAdapter(container); const server = new InversifyHttpServer( { httpAdapter }, container ); await server.build({ routeInfo: true, }); server.listen(3000, () => { console.log("Server listening on port 3000"); }); } bootstrap(); ``` -------------------------------- ### Install Fastify Adapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Install the Inversify HTTP adapter for Fastify. ```bash npm install @inversifyjs/http-fastify ``` -------------------------------- ### Quick Start: Ajv Validation in Inversify Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/validation-docs/ajv/introduction.mdx This example demonstrates setting up Ajv validation for an API endpoint in an Inversify application. Ensure Ajv and the validation package are installed. ```typescript import { Container } from "inversify"; import { controller, httpPost, requestBody, response } from "inversify-express-utils"; import { AjvValidationPipe } from "@inversifyjs/ajv-validation"; // Define the JSON schema for user data const userSchema = { type: "object", properties: { username: { type: "string", minLength: 3 }, email: { type: "string", format: "email" }, }, required: ["username", "email"], }; @controller("/users") class UserController { @httpPost("/", new AjvValidationPipe(userSchema)) create( @requestBody() body: { username: string; email: string }, @response() res: any ): Promise { // Controller logic here, body is already validated return res.status(201).json({ message: "User created successfully", user: body }); } } // --- Container setup (example) --- const container = new Container(); container.bind(UserController).toSelf(); // In a real Express app, you would bind controllers to express-utils // and then use the container to build your application. console.log("UserController setup complete. Ready to handle requests."); ``` -------------------------------- ### Install Express Adapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Install the Inversify HTTP adapter for Express. ```bash npm install @inversifyjs/http-express ``` -------------------------------- ### Install Hono Adapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Install the Inversify HTTP adapter for Hono. ```bash npm install @inversifyjs/http-hono ``` -------------------------------- ### Install uWebSockets.js Adapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Install the Inversify HTTP adapter for uWebSockets.js. ```bash npm install @inversifyjs/http-uwebsockets ``` -------------------------------- ### Install InversifyFastifyHttpAdapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-fastify-http-adapter.mdx Install the necessary packages for using InversifyFastifyHttpAdapter with your preferred package manager. ```bash npm install @inversifyjs/http-fastify fastify inversify reflect-metadata ``` ```bash yarn add @inversifyjs/http-fastify fastify inversify reflect-metadata ``` ```bash pnpm add @inversifyjs/http-fastify fastify inversify reflect-metadata ``` -------------------------------- ### Install InversifyJS and reflect-metadata Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/introduction/getting-started.mdx Install the necessary packages using npm. Ensure you have Node.js and npm installed. ```bash npm install inversify reflect-metadata ``` -------------------------------- ### Example: Decorating a Controller Method with Get Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/decorators.mdx Illustrates using the @Get decorator to bind a controller method to handle GET requests for a given route path. ```typescript const decoratorApiGetSource = `...`; ``` -------------------------------- ### Install @inversifyjs/http-sse Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/ecosystem/sse.mdx Install the SSE package. Ensure @inversifyjs/framework-core and @inversifyjs/http-core are installed as peer dependencies. ```bash npm install @inversifyjs/http-sse ``` -------------------------------- ### Add Code Example to InversifyJS Docs Source: https://github.com/inversify/monorepo/blob/main/packages/docs/tools/inversify-graphql-code-examples/README.md Follow these steps to add a new code example. Ensure examples are placed in the `src/examples` folder and verified with integration tests. ```markdown # @inversifyjs/graphql-code-examples Inversify docs code examples. ## Adding code examples 1. Just create your code example in the `src/examples` folder with an integration test to verify the expected behavior. - Use a `// Begin-example` comment to set the beginning of the example. - Use a `// Exclude-from-example` comment to exclude a sentence from the example. - Use a `// Is-inversify-import-example` comment to normalize inversify imports. - Use a `// End-example` comment to set the end of the example. - Use a `// Shift-line-spaces-2` comment to shift lines 2 spaces to the left. The comment's scope is the whole source file. 2. Run the `build` script. 3. Your code example will be available in the `generated/examples` folder. ``` -------------------------------- ### Basic Usage Example for InversifyExpressHttpAdapter (Express 4) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-express4-http-adapter.mdx Demonstrates the basic setup and usage of the InversifyExpressHttpAdapter with an Express 4 application. ```typescript import "reflect-metadata"; import { Container, inject, injectable, interfaces, } from "inversify"; import { controller, httpGet, InversifyExpressServer, } from "inversify-express-utils"; import { InversifyExpressHttpAdapter, ExpressHttpAdapterOptions, } from "@inversifyjs/http-express-v4"; // Define a controller @injectable() class PingController { @httpGet("/ping") public ping(): string { return "pong"; } } // Create a new Inversify container const container = new Container(); // Bind the controller to the container container.bind(PingController).toSelf(); // Create an Express 4 adapter instance const httpAdapter = new InversifyExpressHttpAdapter(container); // Create a new InversifyExpressServer const server = new InversifyExpressServer(container, httpAdapter); // Build the Express application server.build().listen(3000, () => { console.log("Server listening on port 3000"); }); ``` -------------------------------- ### ContainerModule API Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/guides/migrating-from-v6.mdx Example of loading a `ContainerModule` with options passed as an object. ```typescript import { Container, ContainerModule, injectable } from "inversify"; @injectable() class MyService {} const myModule = new ContainerModule((bind) => { bind(MyService).to(MyService); }); const container = new Container(); container.load(myModule, { // options }); ``` -------------------------------- ### Install @inversifyjs/plugin-dispose and inversify Source: https://github.com/inversify/monorepo/blob/main/packages/container/libraries/plugin-dispose/README.md Install the necessary packages for using the plugin. ```bash npm install @inversifyjs/plugin-dispose inversify ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/inversify/monorepo/blob/main/docs/setup.md Install all project dependencies using the pnpm package manager. Ensure pnpm is installed globally. ```bash pnpm i ``` -------------------------------- ### Install InversifyJS and Dependencies Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-binding-decorators-site/docs/introduction/getting-started.mdx Install inversify, @inversifyjs/binding-decorators, and reflect-metadata using npm. ```bash npm install inversify @inversifyjs/binding-decorators reflect-metadata ``` -------------------------------- ### Basic Usage Example for Hono Adapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx A fundamental example demonstrating how to use the InversifyHonoHttpAdapter in a Hono application. ```typescript import "reflect-metadata"; import { Container } from "inversify"; import { HonoHttpAdapter } from "@inversifyjs/http-hono"; import { Controller } from "@inversifyjs/core"; import { Get, Request, Response, Next } from "@inversifyjs/http-universal"; // Define a controller @Controller("/users") class UsersController { @Get("/:id") getById(@Request() req: any, @Response() res: any, @Next() next: any) { res.send(`User with id ${req.params.id} not found.`); } } // Create a container and bind controllers const container = new Container(); container.bind(UsersController).toSelf(); // Create an instance of the Hono HTTP adapter const httpAdapter = new HonoHttpAdapter(container); // Build the Hono application const app = httpAdapter.build(); // Export the Hono application export type AppType = typeof app; export default app; ``` -------------------------------- ### Install ESLint Plugin Source: https://github.com/inversify/monorepo/blob/main/packages/foundation/tools/eslint-plugin-require-extensions/README.md Install the plugin as a development dependency using pnpm. ```bash pnpm add -D @inversifyjs/eslint-plugin-require-extensions ``` -------------------------------- ### Example: Console logging Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/logger-docs/api.mdx Basic example of initializing and using the ConsoleLogger to log messages to the console. ```typescript import { ConsoleLogger } from 'inversify-logger'; // Initialize ConsoleLogger with a context name const logger = new ConsoleLogger('my-app'); logger.info('Application started.'); logger.warn('A potential issue detected.'); logger.error('An unexpected error occurred.'); ``` -------------------------------- ### Usage Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-express-http-adapter.mdx A basic usage example demonstrating how to set up and use the InversifyExpressHttpAdapter with an Express 5 application. ```APIDOC ## Usage Example {adapterBasicUsageExpressSource} ``` -------------------------------- ### InversifyHonoHttpAdapter Installation Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx Install the necessary packages for using InversifyJS with Hono. ```APIDOC ## Installation Install the necessary packages for using InversifyJS with Hono. ### npm ```bash npm install @inversifyjs/http-hono hono inversify reflect-metadata ``` ### yarn ```bash yarn add @inversifyjs/http-hono hono inversify reflect-metadata ``` ### pnpm ```bash pnpm add @inversifyjs/http-hono hono inversify reflect-metadata ``` ``` -------------------------------- ### Install Dependencies (npm) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/graphql-docs/introduction/getting-started.mdx Install the necessary packages for Inversify GraphQL using npm. ```bash npm install @inversifyjs/apollo-express @inversifyjs/apollo-core @apollo/server graphql ``` -------------------------------- ### InversifyHonoHttpAdapter Usage Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx A basic usage example demonstrating how to integrate InversifyJS with Hono. ```APIDOC ## Usage Example {adapterBasicUsageHonoSource} ``` -------------------------------- ### Install Dependencies (yarn) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/graphql-docs/introduction/getting-started.mdx Install the necessary packages for Inversify GraphQL using yarn. ```bash yarn add @inversifyjs/apollo-express @inversifyjs/apollo-core @apollo/server graphql ``` -------------------------------- ### Install Express v4 Adapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Install the Inversify HTTP adapter for Express v4. ```bash npm install @inversifyjs/http-express-v4 ``` -------------------------------- ### Install @inversifyjs/strongly-typed Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/ecosystem/strongly-typed.mdx Install the strongly-typed package using npm, pnpm, or yarn. ```bash npm install @inversifyjs/strongly-typed ``` ```bash pnpm add @inversifyjs/strongly-typed ``` ```bash yarn add @inversifyjs/strongly-typed ``` -------------------------------- ### Install InversifyUwebSocketsHttpAdapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-uwebsockets-http-adapter.mdx Install the necessary packages for using InversifyJS with uWebSockets.js. This includes the adapter, uWebSockets.js itself, and core InversifyJS dependencies. ```bash npm install @inversifyjs/http-uwebsockets uWebSockets.js inversify reflect-metadata ``` ```bash yarn add @inversifyjs/http-uwebsockets uWebSockets.js inversify reflect-metadata ``` ```bash pnpm add @inversifyjs/http-uwebsockets uWebSockets.js inversify reflect-metadata ``` -------------------------------- ### Example: Binding services through ContainerModule API Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/api/container-module.mdx A code example demonstrating how to use the ContainerModule API to bind services. ```APIDOC ## Example: ContainerModule API Usage ### Description This example illustrates the practical application of the `ContainerModule` API for registering services within an InversifyJS application. It shows how to define a module and load it into a container. ### Request Example ```typescript import { Container, ContainerModule } from 'inversify'; import { TYPES } from './types'; // Assuming TYPES is defined elsewhere // Define your service interfaces and implementations interface MyService { getData(): string; } class MyServiceImpl implements MyService { getData(): string { return 'Data from MyServiceImpl'; } } // Create a ContainerModule const myServiceModule = new ContainerModule((bind) => { bind(TYPES.MyService).to(MyServiceImpl); }); // Create a container and load the module const container = new Container(); container.load(myServiceModule); // Resolve the service const myService = container.get(TYPES.MyService); console.log(myService.getData()); // Output: Data from MyServiceImpl ``` ### Response Example ``` Data from MyServiceImpl ``` ``` -------------------------------- ### Install Dependencies (pnpm) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/graphql-docs/introduction/getting-started.mdx Install the necessary packages for Inversify GraphQL using pnpm. ```bash pnpm install @inversifyjs/apollo-express @inversifyjs/apollo-core @apollo/server graphql ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx Install the necessary packages for using InversifyJS with Hono via npm. ```bash npm install @inversifyjs/http-hono hono inversify reflect-metadata ``` -------------------------------- ### Install Packages with npm Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/faq/migrating-from-inversify-express-utils.mdx Install the necessary packages for Express 5 or Express 4 using npm. ```bash npm install @inversifyjs/http-core @inversifyjs/http-express # Or for Express 4 npm install @inversifyjs/http-core @inversifyjs/http-express-v4 ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx Install the necessary packages for using InversifyJS with Hono via pnpm. ```bash pnpm add @inversifyjs/http-hono hono inversify reflect-metadata ``` -------------------------------- ### Basic Usage Example for InversifyExpressHttpAdapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-express-http-adapter.mdx A fundamental example demonstrating how to set up and use the InversifyExpressHttpAdapter with an Express 5 application. ```typescript import { Container } from "inversify"; import { InversifyExpressHttpAdapter } from "@inversifyjs/http-express"; // Assume controllers, middleware, etc. are configured in the container const container = new Container(); // Create an instance of the adapter const httpAdapter = new InversifyExpressHttpAdapter(container); // Build the Express application httpAdapter.build().then(app => { // Start the server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server listening on port ${port}`); }); }); ``` -------------------------------- ### Install Inversify HTTP Core Dependencies (npm) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Install the core Inversify packages and reflect-metadata using npm. ```bash npm install inversify reflect-metadata @inversifyjs/http-core ``` -------------------------------- ### Install Suites for InversifyJS 6.x Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/ecosystem/suites.mdx Install the necessary packages for InversifyJS 6.x. Use alternative doubles packages for Vitest or Sinon. ```bash npm install -D @suites/unit @suites/di.inversify@^3.0.0 @suites/doubles.jest ``` -------------------------------- ### InversifyExpressHttpAdapter Usage Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-express4-http-adapter.mdx A basic usage example demonstrating how to set up and use the InversifyExpressHttpAdapter with Express 4. ```APIDOC ## Usage Example {adapterBasicUsageExpress4Source} ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx Install the necessary packages for using InversifyJS with Hono via Yarn. ```bash yarn add @inversifyjs/http-hono hono inversify reflect-metadata ``` -------------------------------- ### Build, Format, and Lint Example Packages Source: https://github.com/inversify/monorepo/blob/main/packages/container/examples/AGENTS.md Use these commands to build example packages to verify compilation, format code for readability, and lint for code quality. ```bash pnpm run build pnpm run format pnpm run lint ``` -------------------------------- ### Install OpenAPI Validation Dependencies Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/validation-docs/openapi/introduction.mdx Install the package and its peer dependencies using npm, yarn, or pnpm. ```bash npm install ajv ajv-formats @inversifyjs/open-api-validation ``` ```bash yarn add ajv ajv-formats @inversifyjs/open-api-validation ``` ```bash pnpm install ajv ajv-formats @inversifyjs/open-api-validation ``` -------------------------------- ### Install Inversify HTTP Core Dependencies (yarn) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Install the core Inversify packages and reflect-metadata using yarn. ```bash yarn add inversify reflect-metadata @inversifyjs/http-core ``` -------------------------------- ### Install, Build, and Test All Packages Source: https://github.com/inversify/monorepo/blob/main/AGENTS.md Commands to set up dependencies, build all packages, and run all tests within the monorepo. ```bash pnpm install pnpm run build pnpm test ``` -------------------------------- ### Install Inversify HTTP Core Dependencies (pnpm) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Install the core Inversify packages and reflect-metadata using pnpm. ```bash pnpm install inversify reflect-metadata @inversifyjs/http-core ``` -------------------------------- ### Install Inversify HTTP OpenAPI Dependencies (npm) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/openapi-docs/introduction/getting-started.mdx Install the necessary Inversify packages and reflect-metadata using npm. ```bash npm install inversify reflect-metadata @inversifyjs/http-core @inversifyjs/http-open-api ``` -------------------------------- ### Example of LazyServiceIdentifier Usage Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/api/lazy-service-identifier.mdx This example demonstrates how to use LazyServiceIdentifier to delay the resolution of a service identifier. It shows the typical setup where a function returning the service identifier is passed to the constructor. ```typescript import { Container, injectable, inject } from 'inversify'; import { LazyServiceIdentifier } from '@inversifyjs/core'; // Define a service identifier using LazyServiceIdentifier const lazyServiceIdentifier = new LazyServiceIdentifier(() => { console.log('Resolving service identifier...'); return 'MyServiceIdentifier'; }); @injectable() class MyService { private identifier: string; constructor(@inject(lazyServiceIdentifier) identifier: string) { this.identifier = identifier; console.log(`MyService initialized with identifier: ${this.identifier}`); } } const container = new Container(); container.bind(lazyServiceIdentifier).toConstantValue('MyServiceIdentifier'); container.bind(MyService).to(MyService); console.log('Container setup complete. Injecting MyService...'); const myService = container.get(MyService); console.log('MyService injected successfully.'); ``` -------------------------------- ### Basic Usage Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-fastify-http-adapter.mdx Demonstrates the basic usage of the InversifyFastifyHttpAdapter with a Fastify application. This example shows how to create an adapter instance and build the Fastify application. ```typescript import "reflect-metadata"; import { Container } from "inversify"; import { InversifyFastifyHttpAdapter } from "@inversifyjs/http-fastify"; async function bootstrap() { const container = new Container(); const httpAdapter = new InversifyFastifyHttpAdapter(container); const app = await httpAdapter.build(); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Install InversifyExpressHttpAdapter Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-express-http-adapter.mdx Install the necessary packages for using InversifyJS with Express 5. This includes the http-express adapter, express, inversify, and reflect-metadata. ```bash npm install @inversifyjs/http-express express inversify reflect-metadata ``` ```bash yarn add @inversifyjs/http-express express inversify reflect-metadata ``` ```bash pnpm add @inversifyjs/http-express express inversify reflect-metadata ``` -------------------------------- ### Create Server and Listen Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/introduction/getting-started.mdx Basic example of setting up an Express server with Inversify HTTP to listen for incoming requests. ```typescript import "reflect-metadata"; import { InversifyHTTP } from "@inversifyjs/http-core"; import { ExpressAdapter } from "@inversifyjs/http-express"; async function bootstrap() { const http = new InversifyHTTP({ container: new Container(), adapter: new ExpressAdapter(), }); await http.start(3000); console.log("Server started on port 3000"); } bootstrap(); ``` -------------------------------- ### Deno Runtime Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx Illustrates how to serve a Hono application using Deno's built-in server. ```typescript // Deno // Deno.serve(app.fetch); ``` -------------------------------- ### Bun Runtime Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx Shows how to configure a Hono application to run with Bun. ```typescript // Bun // export default { // port: 3000, // fetch: app.fetch, // }; ``` -------------------------------- ### Basic BetterAuth Usage Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/ecosystem/better-auth/api/better-auth.mdx Demonstrates the basic setup and usage of the BetterAuth type. Ensure Better Auth is installed and configured before use. ```typescript import { Container } from 'inversify'; import { betterAuth, BetterAuthOptions } from 'better-auth'; import type { BetterAuth } from '@inversifyjs/better-auth'; // Define your specific Better Auth options interface MyBetterAuthOptions extends BetterAuthOptions { // ... your custom options } // Create a Better Auth instance with your options const myBetterAuth = betterAuth({ // ... your configuration }); // Use the BetterAuth type for type safety const container = new Container(); container .bind>('BetterAuth') .toConstantValue(myBetterAuth); // Now you can resolve the typed BetterAuth instance from the container const auth = container.get>('BetterAuth'); // You can now use auth with full type safety based on MyBetterAuthOptions ``` -------------------------------- ### Custom User Session Parameter Decorator Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/decorators.mdx Example of creating a custom parameter decorator to access user session data. Requires a custom IoC container setup. ```typescript import { interfaces } from "inversify"; import { httpParamDecorator } from "inversify-express-utils"; export function UserSession(): (target: any, key: string, index: number) => void { return httpParamDecorator((request: any, response: any, next: () => void) => { return request.session.user; }); } export class UserController { @httpGet("/users/me") public me(@UserSession() userSession: UserSession) { return userSession.user; } } ``` -------------------------------- ### DI Hierarchy Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/fundamentals/di-hierarchy.mdx Illustrates a basic DI hierarchy where a child container can resolve dependencies from its parent. This setup helps in organizing and managing dependencies across different application layers. ```typescript import { Container, injectable, inject } from "inversify"; import "reflect-metadata"; // Define interfaces interface IWarrior { fight(): string; sneak(): string; } interface IKunai { hit(): string; } // Bindings for the parent container @injectable() class Katana implements IKunai { hit() { return "cut!"; } } @injectable() class Ninja implements IWarrior { private _kunai: IKunai; public constructor(@inject(IKunai) kunai: IKunai) { this._kunai = kunai; } public fight(): string { return this.sneak() + this.kunai.hit(); } public sneak(): string { return "am stealthy "; } public get kunai(): IKunai { return this._kunai; } } // Create parent container and bind const parentContainer = new Container(); parentContainer.bind(IKunai).to(Katana); // Create child container and bind const childContainer = new Container(); childContainer.bind(IWarrior).to(Ninja); // Inject dependencies const ninja = childContainer.get(IWarrior); // Demonstrate resolution console.log(ninja.fight()); // Output: am stealthy cut! ``` -------------------------------- ### Test method scope with mocked dependencies Source: https://github.com/inversify/monorepo/blob/main/docs/testing/unit-testing.md This example shows how to structure tests for a specific method (`.sayHello`) within a class. It follows the class scope setup and adds a nested `describe` block for the method. ```typescript describe(Foo, () => { let barMock: Mocked; let foo: Foo; beforeAll(() => { barMock = { ... }; foo = new Foo(barMock); }); describe('.sayHello', () => { ... }); }); ``` -------------------------------- ### Initialize uWebSockets.js Adapter and Build App Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/blog/2025-11-04-uwebsockets-adapter/index.md Instantiate the adapter with a container and configuration options. Build the application and start the server, specifying the host and port. ```typescript import { InversifyUwebSocketsHttpAdapter, } from '@inversifyjs/http-uwebsockets'; import { Container } from 'inversify'; const adapter = new InversifyUwebSocketsHttpAdapter(container, { logger: true, useJson: true, }); const app = await adapter.build(); app.listen('0.0.0.0', 3000, (socket) => { console.log('Server running at lightning speed 🚀'); }); ``` -------------------------------- ### Example: Configuring logger options Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/logger-docs/api.mdx Illustrates how to configure logger options, including specifying which log levels to process and whether to include timestamps. ```typescript import { Logger, LogLevel, LoggerOptions, ConsoleLogger } from 'inversify-logger'; const loggerOptions: LoggerOptions = { json: true, // Enable JSON formatting logTypes: [LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR, LogLevel.DEBUG], timestamp: true, // Include timestamps }; const logger: Logger = new ConsoleLogger('my-app-json', loggerOptions); logger.info('This is an informational message.'); logger.debug('This is a debug message.'); logger.warn('This is a warning message.'); ``` -------------------------------- ### Node.js Runtime Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-hono-http-adapter.mdx Shows how to serve a Hono application using the Node.js runtime. ```typescript // Node.js import { serve } from '@hono/node-server'; // Assuming 'app' is your Hono instance // serve({ fetch: app.fetch, port: 3000 }); ``` -------------------------------- ### Install InversifyExpressHttpAdapter for Express 4 Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/inversify-http-adapter/inversify-express4-http-adapter.mdx Install the necessary packages for using InversifyJS with Express 4. Ensure you have Express version 4.x installed. ```bash npm install @inversifyjs/http-express-v4 express@^4.0.0 inversify reflect-metadata ``` ```bash yarn add @inversifyjs/http-express-v4 express@^4.0.0 inversify reflect-metadata ``` ```bash pnpm add @inversifyjs/http-express-v4 express@^4.0.0 inversify reflect-metadata ``` -------------------------------- ### Install @inversifyjs/logger with pnpm Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/logger-docs/introduction/getting-started.mdx Use pnpm to install the @inversifyjs/logger package. ```bash pnpm install @inversifyjs/logger ``` -------------------------------- ### Real-time Chat Example with SSE Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/ecosystem/sse.mdx Build a broadcast-style chat system using SSE. This example demonstrates managing multiple streams and broadcasting messages to all connected clients. ```typescript import { controller, httpGet, httpPost } from "@inversify/http-core"; import { SsePublisher } from "@inversifyjs/http-sse"; import { injectable } from "@inversify/core"; interface ChatMessage { user: string; message: string; } @injectable() export class ChatService { private streams = new Set(); public addStream(stream: SsePublisher) { this.streams.add(stream); stream.on("close", () => { this.streams.delete(stream); }); } public broadcast(message: ChatMessage) { this.streams.forEach((stream) => { stream({ data: JSON.stringify(message) }); }); } } @controller("/chat") export class ChatController { constructor(private chatService: ChatService) {} @httpGet("/stream") public stream(@SsePublisher() publish: SsePublisher) { this.chatService.addStream(publish); } @httpPost("/send") public send( // Assume request body is ChatMessage request: { body: ChatMessage } ) { this.chatService.broadcast(request.body); } } ``` -------------------------------- ### Install @inversifyjs/logger with yarn Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/logger-docs/introduction/getting-started.mdx Use yarn to install the @inversifyjs/logger package. ```bash yarn add @inversifyjs/logger ``` -------------------------------- ### Run Integration Tests for Examples Source: https://github.com/inversify/monorepo/blob/main/packages/docs/tools/AGENTS.md Execute integration tests to verify that the code examples function correctly. This command runs the default test suite, which includes integration tests. ```bash pnpm run test:integration ``` ```bash pnpm run test ``` -------------------------------- ### Install @inversifyjs/logger with npm Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/logger-docs/introduction/getting-started.mdx Use npm to install the @inversifyjs/logger package. ```bash npm install @inversifyjs/logger ``` -------------------------------- ### Creating the Initial List Source: https://github.com/inversify/monorepo/blob/main/packages/container/libraries/core/docs/single-immutable-linked-list.md Algorithm for creating the first node and list instance. Requires a single element to initialize. ```pseudocode function listCreate(elem): List node := { elem, previous: undefined } return new List(node) ``` -------------------------------- ### POST Request Setup Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/decorators.mdx Sets up a route for POST requests. The path parameter specifies the route path, defaulting to '/'. ```APIDOC ## POST /api/resource ### Description Sets up a route for POST requests. ### Method POST ### Endpoint /api/resource ### Parameters #### Path Parameters - **path** (string) - Optional - Route path mounted under the controller's base path. Defaults to '/'. Example: `@Post('/create')` maps to `POST /create`. ### Request Example ```json { "key": "value" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Resource created successfully" } ``` ``` -------------------------------- ### Example: Using the Logger interface Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/logger-docs/api.mdx Demonstrates how to use the core Logger interface for logging messages across different levels. ```typescript import { Logger, LogLevel, LoggerOptions, ContextMetadata } from 'inversify-logger'; const loggerOptions: LoggerOptions = { logTypes: [LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR], timestamp: true, }; const logger = new ConsoleLogger('my-app', loggerOptions); const contextMetadata: ContextMetadata = { requestId: '12345', userId: 'abcde', }; logger.info('Application started successfully.', contextMetadata); logger.warn('Configuration file not found, using defaults.', { context: 'config-loader' }); logger.error('Database connection failed.', { error: new Error('Connection refused') }); // This log will not be shown because LogLevel.DEBUG is not included in logTypes logger.debug('Debugging information.'); // Using the generic log method logger.log(LogLevel.INFO, 'Another info message.'); ``` -------------------------------- ### Basic InversifyJS Example Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/introduction/getting-started.mdx Demonstrates initializing a container, defining injectable classes with decorators, and setting up basic dependency injection. Requires experimental decorators and emit decorator metadata to be enabled in tsconfig.json. ```typescript import { Container, injectable, inject } from "inversify"; import "reflect-metadata"; const TYPES = { Katana: Symbol.for("Katana"), Ninja: Symbol.for("Ninja") }; @injectable() class Katana { public hit() { return "cut!"; } } @injectable() class Ninja { private katana: Katana; constructor(@inject(TYPES.Katana) katana: Katana) { this.katana = katana; } public fight() { return this.katana.hit(); } } const container = new Container(); container.bind(TYPES.Katana).to(Katana); container.bind(TYPES.Ninja).to(Ninja); const ninja = container.get(TYPES.Ninja); console.log(ninja.fight()); // "cut!" ``` -------------------------------- ### Add Code Example to InversifyJS Docs Source: https://github.com/inversify/monorepo/blob/main/packages/docs/tools/inversify-http-code-examples/README.md Use specific comments within your code files to manage how examples are processed. Begin examples with `// Begin-example`, exclude lines with `// Exclude-from-example`, normalize imports with `// Is-inversify-import-example`, end examples with `// End-example`, and shift lines with `// Shift-line-spaces-2`. ```javascript // Begin-example // Exclude-from-example // Is-inversify-import-example // Shift-line-spaces-2 console.log('This is an example line.'); // End-example ``` -------------------------------- ### Install InversifyJS Beta with npm Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/blog/2026-03-01-announcing-inversify-8-0-0-beta-0/index.mdx Use this command to install the beta version of InversifyJS using npm. This is for testing the upcoming 8.0.0 release. ```bash npm install inversify@8.0.0-beta.0 ``` -------------------------------- ### Install class-validator Dependencies Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/validation-docs/introduction/getting-started.mdx Install class-validator, class-transformer, and the InversifyJS class validation package. ```bash npm install class-validator class-transformer @inversifyjs/class-validation ``` -------------------------------- ### Install Ajv Validation Dependencies Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/validation-docs/introduction/getting-started.mdx Install Ajv and the InversifyJS Ajv validation package. ```bash npm install ajv @inversifyjs/ajv-validation ``` -------------------------------- ### ApolloSubscriptionServerContainerModule Setup Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/graphql-docs/api/apollo-subscription-ws.mdx Demonstrates how to configure and load the ApolloSubscriptionServerContainerModule to enable GraphQL subscriptions. ```APIDOC ## ApolloSubscriptionServerContainerModule ### Description The `ApolloSubscriptionServerContainerModule` is a container module designed to set up and configure the GraphQL subscription server using `graphql-ws`. ### Constructor ```typescript constructor(options?: ApolloSubscriptionServerContainerModuleOptions) ``` ### Parameters #### `ApolloSubscriptionServerContainerModuleOptions` An interface defining the configuration options for the subscription server. - **path** (`string`) - Optional - The specific path where the WebSocket server will listen for connections. If not provided, it defaults to `/subscriptions`. ### Usage Example ```typescript import { ApolloSubscriptionServerContainerModule } from '@inversifyjs/apollo-subscription-ws'; // Assuming 'container' is an initialized InversifyJS container instance await container.load( new ApolloSubscriptionServerContainerModule({ path: '/subscriptions', }) ); ``` ``` -------------------------------- ### Example: Decorating a Controller Method with All Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/decorators.mdx Demonstrates applying the @All decorator to a controller method to handle requests for all HTTP methods on a specific path. ```typescript const decoratorApiAllSource = `...`; ``` -------------------------------- ### API Decorator - Get Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-framework-site/docs/api/decorators.mdx Defines a GET HTTP endpoint. Use for retrieving resources. ```typescript import { controller, httpGet } from "inversify-express-utils"; @controller("/api/v1/users") export class UsersController { @httpGet("/:id") public getUser(request: ExpressRequest): Promise { const id = request.params.id; return Promise.resolve(new User(id)); } } ``` -------------------------------- ### Standard Resolution Mode Example (getAll) Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/docs/fundamentals/di-hierarchy.mdx Shows how `getAll()` behaves in standard resolution mode. It only returns bindings from the current container, ignoring parent bindings if a match is found locally. This is the default behavior. ```typescript import { Container, injectable, inject } from "inversify"; import "reflect-metadata"; // Define interfaces interface IWarrior { fight(): string; sneak(): string; } interface IKunai { hit(): string; } // Bindings for the parent container @injectable() class Katana implements IKunai { hit() { return "cut!"; } } @injectable() class Shuriken implements IKunai { hit() { return "uriken!"; } } @injectable() class Ninja implements IWarrior { private _kunai: IKunai; public constructor(@inject(IKunai) kunai: IKunai) { this._kunai = kunai; } public fight(): string { return this.sneak() + this.kunai.hit(); } public sneak(): string { return "am stealthy "; } public get kunai(): IKunai { return this._kunai; } } // Create parent container and bind const parentContainer = new Container(); parentContainer.bind(IKunai).to(Katana); // Create child container and bind const childContainer = new Container(); childContainer.bind(IKunai).to(Shuriken); childContainer.bind(IWarrior).to(Ninja); // Inject dependencies const ninja = childContainer.get(IWarrior); // Demonstrate resolution console.log(ninja.fight()); // Output: am stealthy uriken! // Demonstrate getAll() behavior in standard mode const kunais = childContainer.getAll(IKunai); console.log(kunais.length); // Output: 1 console.log(kunais[0] instanceof Shuriken); // Output: true ``` -------------------------------- ### Install InversifyJS with yarn Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/blog/2026-03-16-announcing-inversify-8-0-0/index.mdx Use this command to install InversifyJS version 8.0.0 using yarn. ```bash yarn add inversify@8.0.0 ``` -------------------------------- ### Install InversifyJS with pnpm Source: https://github.com/inversify/monorepo/blob/main/packages/docs/services/inversify-site/blog/2026-03-16-announcing-inversify-8-0-0/index.mdx Use this command to install InversifyJS version 8.0.0 using pnpm. ```bash pnpm add inversify@8.0.0 ```