{"id":13512477,"url":"https://github.com/inversify/inversify-express-utils","last_synced_at":"2025-03-30T22:32:50.640Z","repository":{"id":8657490,"uuid":"59208533","full_name":"inversify/inversify-express-utils","owner":"inversify","description":"Some utilities for the development of Express application with InversifyJS","archived":false,"fork":false,"pushed_at":"2024-10-25T23:51:26.000Z","size":893,"stargazers_count":583,"open_issues_count":20,"forks_count":100,"subscribers_count":23,"default_branch":"master","last_synced_at":"2024-10-29T14:19:30.500Z","etag":null,"topics":["dependency-injection","dependency-injection-container","dependency-injection-framework","express","inversify","inversion-of-control","javascript","nodejs","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/inversify.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-05-19T13:24:29.000Z","updated_at":"2024-10-25T23:51:26.000Z","dependencies_parsed_at":"2024-04-02T12:55:03.814Z","dependency_job_id":"d0d69203-2d2e-44a3-b5e0-38704d1e9ae4","html_url":"https://github.com/inversify/inversify-express-utils","commit_stats":{"total_commits":366,"total_committers":41,"mean_commits":8.926829268292684,"dds":0.5601092896174864,"last_synced_commit":"81933b662f7546c6f7da98e643bd18e52f550231"},"previous_names":[],"tags_count":49,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inversify%2Finversify-express-utils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inversify%2Finversify-express-utils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inversify%2Finversify-express-utils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/inversify%2Finversify-express-utils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/inversify","download_url":"https://codeload.github.com/inversify/inversify-express-utils/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245984579,"owners_count":20704797,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dependency-injection","dependency-injection-container","dependency-injection-framework","express","inversify","inversion-of-control","javascript","nodejs","typescript"],"created_at":"2024-08-01T03:01:54.183Z","updated_at":"2025-03-30T22:32:45.630Z","avatar_url":"https://github.com/inversify.png","language":"TypeScript","readme":"# inversify-express-utils\n\n[![Join the chat at https://gitter.im/inversify/InversifyJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/inversify/InversifyJS?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n[![Build Status](https://secure.travis-ci.org/inversify/inversify-express-utils.svg?branch=master)](https://travis-ci.org/inversify/inversify-express-utils)\n[![Test Coverage](https://codeclimate.com/github/inversify/inversify-express-utils/badges/coverage.svg)](https://codeclimate.com/github/inversify/inversify-express-utils/coverage)\n[![npm version](https://badge.fury.io/js/inversify-express-utils.svg)](http://badge.fury.io/js/inversify-express-utils)\n[![Dependencies](https://david-dm.org/inversify/inversify-express-utils.svg)](https://david-dm.org/inversify/inversify-express-utils#info=dependencies)\n[![img](https://david-dm.org/inversify/inversify-express-utils/dev-status.svg)](https://david-dm.org/inversify/inversify-express-utils/#info=devDependencies)\n[![img](https://david-dm.org/inversify/inversify-express-utils/peer-status.svg)](https://david-dm.org/inversify/inversify-express-utils/#info=peerDependenciess)\n[![Known Vulnerabilities](https://snyk.io/test/github/inversify/inversify-express-utils/badge.svg)](https://snyk.io/test/github/inversify/inversify-express-utils)\n\n[![NPM](https://nodei.co/npm/inversify-express-utils.png?downloads=true\u0026downloadRank=true)](https://nodei.co/npm/inversify-express-utils/)\n[![NPM](https://nodei.co/npm-dl/inversify-express-utils.png?months=9\u0026height=3)](https://nodei.co/npm/inversify-express-utils/)\n\nSome utilities for the development of express applications with Inversify.\n\n## Installation\n\nYou can install `inversify-express-utils` using npm:\n\n```sh\nnpm install inversify inversify-express-utils reflect-metadata --save\n```\n\nThe `inversify-express-utils` type definitions are included in the npm module and require TypeScript 2.0.\nPlease refer to the [InversifyJS documentation](https://github.com/inversify/InversifyJS#installation) to learn more about the installation process.\n\n## The Basics\n\n### Step 1: Decorate your controllers\n\nTo use a class as a \"controller\" for your express app, simply add the `@controller` decorator to the class. Similarly, decorate methods of the class to serve as request handlers.\n\nThe following example will declare a controller that responds to `GET /foo'.\n\n```ts\nimport * as express from \"express\";\nimport { interfaces, controller, httpGet, httpPost, httpDelete, request, queryParam, response, requestParam } from \"inversify-express-utils\";\nimport { injectable, inject } from \"inversify\";\n\n@controller(\"/foo\")\nexport class FooController implements interfaces.Controller {\n\n    constructor( @inject(\"FooService\") private fooService: FooService ) {}\n\n    @httpGet(\"/\")\n    private index(@request() req: express.Request, @response() res: express.Response, @next() next: express.NextFunction): string {\n        return this.fooService.get(req.query.id);\n    }\n\n    @httpGet(\"/\")\n    private list(@queryParam(\"start\") start: number, @queryParam(\"count\") count: number): string {\n        return this.fooService.get(start, count);\n    }\n\n    @httpPost(\"/\")\n    private async create(@request() req: express.Request, @response() res: express.Response) {\n        try {\n            await this.fooService.create(req.body);\n            res.sendStatus(201);\n        } catch (err) {\n            res.status(400).json({ error: err.message });\n        }\n    }\n\n    @httpDelete(\"/:id\")\n    private delete(@requestParam(\"id\") id: string, @response() res: express.Response): Promise\u003cvoid\u003e {\n        return this.fooService.delete(id)\n            .then(() =\u003e res.sendStatus(204))\n            .catch((err: Error) =\u003e {\n                res.status(400).json({ error: err.message });\n            });\n    }\n}\n```\n\n### Step 2: Configure container and server\n\nConfigure the inversify container in your composition root as usual.\n\nThen, pass the container to the InversifyExpressServer constructor. This will allow it to register all controllers and their dependencies from your container and attach them to the express app.\nThen just call server.build() to prepare your app.\n\nIn order for the InversifyExpressServer to find your controllers, you must bind them to the `TYPE.Controller` service identifier and tag the binding with the controller's name.\nThe `Controller` interface exported by inversify-express-utils is empty and solely for convenience, so feel free to implement your own if you want.\n\n```ts\nimport * as bodyParser from 'body-parser';\n\nimport { Container } from 'inversify';\nimport { interfaces, InversifyExpressServer, TYPE } from 'inversify-express-utils';\n\n// declare metadata by @controller annotation\nimport \"./controllers/foo_controller\";\n\n// set up container\nlet container = new Container();\n\n// set up bindings\ncontainer.bind\u003cFooService\u003e('FooService').to(FooService);\n\n// create server\nlet server = new InversifyExpressServer(container);\nserver.setConfig((app) =\u003e {\n  // add body parser\n  app.use(bodyParser.urlencoded({\n    extended: true\n  }));\n  app.use(bodyParser.json());\n});\n\nlet app = server.build();\napp.listen(3000);\n```\n\n## Important information about the @controller decorator\n\nSince the `inversify-express-util@5.0.0` release. The `@injectable` annotation is no longer required in classes annotated with `@controller`. Declaring a type binding for controllers is also no longer required in classes annotated with `@controller`.\n\n:warning: Declaring a binding is not required for Controllers but **it is required to import the controller one unique time**. When the controller file is imported (e.g. `import \"./controllers/some_controller\"`) the class is declared and the metadata is generated. If you don't import it the metadata is never generated and therefore the controller is not found. An example of this can be found [here](https://github.com/inversify/inversify-express-example/blob/master/MongoDB/bootstrap.ts#L10-L11).\n\nIf you run the application multiple times within a shared runtime process (e.g. unit testing) you might need to clean up the existing metadata before each test.\n\n```ts\nimport { cleanUpMetadata } from \"inversify-express-utils\";\n\ndescribe(\"Some Component\", () =\u003e {\n\n    beforeEach(() =\u003e {\n        cleanUpMetadata();\n    });\n\n    it(\"Some test case\", () =\u003e {\n        // ...\n    });\n\n});\n```\n\nYou can find an example of this in [our unit tests](https://github.com/inversify/inversify-express-utils/blob/master/test/framework.test.ts#L25-L29).\n\nInversify express utils will throw an exception if your application doesn't have controllers. You can disable this behaviour using the `forceControllers` option. You can find some examples of `forceControllers` in [our unit tests](https://github.com/inversify/inversify-express-utils/blob/master/test/issue_590.test.ts).\n\n## InversifyExpressServer\n\nA wrapper for an express Application.\n\n### `.setConfig(configFn)`\n\nOptional - exposes the express application object for convenient loading of server-level middleware.\n\n```ts\nimport * as morgan from 'morgan';\n// ...\nlet server = new InversifyExpressServer(container);\n\nserver.setConfig((app) =\u003e {\n    var logger = morgan('combined')\n    app.use(logger);\n});\n```\n\n### `.setErrorConfig(errorConfigFn)`\n\nOptional - like `.setConfig()`, except this function is applied after registering all app middleware and controller routes.\n\n```ts\nlet server = new InversifyExpressServer(container);\nserver.setErrorConfig((app) =\u003e {\n    app.use((err, req, res, next) =\u003e {\n        console.error(err.stack);\n        res.status(500).send('Something broke!');\n    });\n});\n```\n\n### `.build()`\n\nAttaches all registered controllers and middleware to the express application. Returns the application instance.\n\n```ts\n// ...\nlet server = new InversifyExpressServer(container);\nserver\n    .setConfig(configFn)\n    .setErrorConfig(errorConfigFn)\n    .build()\n    .listen(3000, 'localhost', callback);\n```\n\n## Using a custom Router\n\nIt is possible to pass a custom `Router` instance to `InversifyExpressServer`:\n\n```ts\nlet container = new Container();\n\nlet router = express.Router({\n    caseSensitive: false,\n    mergeParams: false,\n    strict: false\n});\n\nlet server = new InversifyExpressServer(container, router);\n```\n\nBy default server will serve the API at `/` path, but sometimes you might need to use different root namespace, for\nexample all routes should start with `/api/v1`. It is possible to pass this setting via routing configuration to\n`InversifyExpressServer`\n\n```ts\nlet container = new Container();\n\nlet server = new InversifyExpressServer(container, null, { rootPath: \"/api/v1\" });\n```\n\n## Using a custom express application\n\nIt is possible to pass a custom `express.Application` instance to `InversifyExpressServer`:\n\n```ts\nlet container = new Container();\n\nlet app = express();\n//Do stuff with app\n\nlet server = new InversifyExpressServer(container, null, null, app);\n```\n\n## Decorators\n\n### `@controller(path, [middleware, ...])`\n\nRegisters the decorated class as a controller with a root path, and optionally registers any global middleware for this controller.\n\n### `@httpMethod(method, path, [middleware, ...])`\n\nRegisters the decorated controller method as a request handler for a particular path and method, where the method name is a valid express routing method.\n\n### `@SHORTCUT(path, [middleware, ...])`\n\nShortcut decorators which are simply wrappers for `@httpMethod`. Right now these include `@httpGet`, `@httpPost`, `@httpPut`, `@httpPatch`, `@httpHead`, `@httpDelete`, `@httpOptions`, and `@All`. For anything more obscure, use `@httpMethod` (Or make a PR :smile:).\n\n### `@request()`\n\nBinds a method parameter to the request object.\n\n### `@response()`\n\nBinds a method parameter to the response object.\n\n### `@requestParam(name: string)`\n\nBinds a method parameter to request.params object or to a specific parameter if a name is passed.\n\n### `@queryParam(name: string)`\n\nBinds a method parameter to request.query or to a specific query parameter if a name is passed.\n\n### `@requestBody()`\n\nBinds a method parameter to the request.body. If the bodyParser middleware is not used on the express app, this will bind the method parameter to the express request object.\n\n### `@requestHeaders(name: string)`\n\nBinds a method parameter to the request headers.\n\n### `@cookies(name: string)`\n\nBinds a method parameter to the request cookies.\n\n### `@next()`\n\nBinds a method parameter to the next() function.\n\n### `@principal()`\n\nBinds a method parameter to the user principal obtained from the AuthProvider.\n\n## BaseHttpController\n\nThe `BaseHttpController` is a base class that provides a significant amount of helper functions in order to aid writing testable controllers.  When returning a response from a method defined on one of these controllers, you may use the `response` object available on the `httpContext` property described in the next section, or you may return an `HttpResponseMessage`, or you may return an object that implements the IHttpActionResult interface.\n\nThe benefit of the latter two methods is that since your controller is no longer directly coupled to requiring an httpContext to send a response, unit testing controllers becomes extraordinarily simple as you no longer need to mock the entire response object, you can simply run assertions on the returned value.  This API also allows us to make future improvements in this area and add in functionality that exists in similar frameworks (.NET WebAPI) such as media formatters, content negotation, etc.\n\n```ts\nimport { injectable, inject } from \"inversify\";\nimport {\n    controller, httpGet, BaseHttpController, HttpResponseMessage, StringContent\n} from \"inversify-express-utils\";\n\n@controller(\"/\")\nclass ExampleController extends BaseHttpController {\n    @httpGet(\"/\")\n    public async get() {\n        const response = new HttpResponseMessage(200);\n        response.content = new StringContent(\"foo\");\n        return response;\n    }\n```\n\nOn the BaseHttpController, we provide a litany of helper methods to ease returning common IHttpActionResults including\n\n* OkResult\n* OkNegotiatedContentResult\n* RedirectResult\n* ResponseMessageResult\n* StatusCodeResult\n* BadRequestErrorMessageResult\n* BadRequestResult\n* ConflictResult\n* CreatedNegotiatedContentResult\n* ExceptionResult\n* InternalServerError\n* NotFoundResult\n* JsonResult\n* StreamResult\n\n```ts\nimport { injectable, inject } from \"inversify\";\nimport {\n    controller, httpGet, BaseHttpController\n} from \"inversify-express-utils\";\n\n@controller(\"/\")\nclass ExampleController extends BaseHttpController {\n    @httpGet(\"/\")\n    public async get() {\n        return this.ok(\"foo\");\n    }\n```\n\n### JsonResult\n\nIn some scenarios, you'll want to set the status code of the response.\nThis can be done by using the `json` helper method provided by `BaseHttpController`.\n\n```ts\nimport {\n    controller, httpGet, BaseHttpController\n} from \"inversify-express-utils\";\n\n@controller(\"/\")\nexport class ExampleController extends BaseHttpController {\n    @httpGet(\"/\")\n    public async get() {\n        const content = { foo: \"bar\" };\n        const statusCode = 403;\n\n        return this.json(content, statusCode);\n    }\n}\n```\n\nThis gives you the flexability to create your own responses while keeping unit testing simple.\n\n```ts\nimport { expect } from \"chai\";\n\nimport { ExampleController } from \"./example-controller\";\nimport { results } from \"inversify-express-utils\";\n\ndescribe(\"ExampleController\", () =\u003e {\n    let controller: ExampleController;\n\n    beforeEach(() =\u003e {\n        controller = new ExampleController();\n    });\n\n    describe(\"#get\", () =\u003e {\n        it(\"should have a status code of 403\", async () =\u003e {\n            const response = await controller.get();\n\n            expect(response).to.be.an.instanceof(results.JsonResult);\n            expect(response.statusCode).to.equal(403);\n        });\n    });\n});\n```\n*This example uses [Mocha](https://mochajs.org) and [Chai](http://www.chaijs.com) as a unit testing framework*\n\n### StreamResult\n\nIn some cases, you'll want to proxy data stream from remote resource in response.\nThis can be done by using the `stream` helper method provided by `BaseHttpController`.\nUseful in cases when you need to return large data.\n\n```ts\nimport { inject } from \"inversify\";\nimport {\n    controller, httpGet, BaseHttpController\n} from \"inversify-express-utils\";\nimport TYPES from \"../constants\";\nimport { FileServiceInterface } from \"../interfaces\";\n\n@controller(\"/cats\")\nexport class CatController extends BaseHttpController {\n    @inject(TYPES.FileService) private fileService: FileServiceInterface;\n\n    @httpGet(\"/image\")\n    public async getCatImage() {\n        const readableStream = this.fileService.getFileStream(\"cat.jpeg\");\n\n        return this.stream(content, \"image/jpeg\", 200);\n    }\n}\n```\n\n## HttpContext\n\nThe `HttpContext` property allow us to access the current request,\nresponse and user with ease. `HttpContext` is available as a property\nin controllers derived from `BaseHttpController`.\n\n```ts\nimport { injectable, inject } from \"inversify\";\nimport {\n    controller, httpGet, BaseHttpController\n} from \"inversify-express-utils\";\n\n@controller(\"/\")\nclass UserPreferencesController extends BaseHttpController {\n\n    @inject(\"AuthService\") private readonly _authService: AuthService;\n\n    @httpGet(\"/\")\n    public async get() {\n        const token = this.httpContext.request.headers[\"x-auth-token\"];\n        return await this._authService.getUserPreferences(token);\n    }\n}\n```\n\nIf you are creating a custom controller you will need to inject `HttpContext` manually\nusing the `@injectHttpContext` decorator:\n\n```ts\nimport { injectable, inject } from \"inversify\";\nimport {\n    controller, httpGet, BaseHttpController, httpContext, interfaces\n} from \"inversify-express-utils\";\n\nconst authService = inject(\"AuthService\")\n\n@controller(\"/\")\nclass UserPreferencesController {\n\n    @injectHttpContext private readonly _httpContext: interfaces.HttpContext;\n    @authService private readonly _authService: AuthService;\n\n    @httpGet(\"/\")\n    public async get() {\n        const token = this.httpContext.request.headers[\"x-auth-token\"];\n        return await this._authService.getUserPreferences(token);\n    }\n}\n```\n\n## AuthProvider\n\nThe `HttpContext` will not have access to the current user if you don't\ncreate a custom `AuthProvider` implementation:\n\n```ts\nconst server = new InversifyExpressServer(\n    container, null, null, null, CustomAuthProvider\n);\n```\n\nWe need to implement the `AuthProvider` interface.\n\nThe `AuthProvider` allow us to get a user (`Principal`):\n\n```ts\nimport { injectable, inject } from \"inversify\";\nimport { interfaces } from \"inversify-express-utils\";\n\nconst authService = inject(\"AuthService\");\n\n@injectable()\nclass CustomAuthProvider implements interfaces.AuthProvider {\n\n    @authService private readonly _authService: AuthService;\n\n    public async getUser(\n        req: express.Request,\n        res: express.Response,\n        next: express.NextFunction\n    ): Promise\u003cinterfaces.Principal\u003e {\n        const token = req.headers[\"x-auth-token\"]\n        const user = await this._authService.getUser(token);\n        const principal = new Principal(user);\n        return principal;\n    }\n\n}\n```\n\nWe also need to implement the Principal interface.\nThe `Principal` interface allow us to:\n\n- Access the details of a user\n- Check if it has access to certain resource\n- Check if it is authenticated\n- Check if it is in a user role\n\n```ts\nclass Principal implements interfaces.Principal\u003cT = unknown\u003e {\n    public details: T;\n    public constructor(details: T) {\n        this.details = details;\n    }\n    public isAuthenticated(): Promise\u003cboolean\u003e {\n        return Promise.resolve(true);\n    }\n    public isResourceOwner(resourceId: unknown): Promise\u003cboolean\u003e {\n        return Promise.resolve(resourceId === 1111);\n    }\n    public isInRole(role: string): Promise\u003cboolean\u003e {\n        return Promise.resolve(role === \"admin\");\n    }\n}\n```\n\nWe can then access the current user (Principal) via the `HttpContext`:\n\n```ts\n@controller(\"/\")\nclass UserDetailsController extends BaseHttpController {\n\n    @inject(\"AuthService\") private readonly _authService: AuthService;\n\n    @httpGet(\"/\")\n    public async getUserDetails() {\n        if (this.httpContext.user.isAuthenticated()) {\n            return this._authService.getUserDetails(this.httpContext.user.details.id);\n        } else {\n            throw new Error();\n        }\n    }\n}\n```\n\n## BaseMiddleware\n\nExtending `BaseMiddleware` allow us to inject dependencies\nand to access the current `HttpContext` in Express middleware function.\n\n```ts\nimport { BaseMiddleware } from \"inversify-express-utils\";\n\n@injectable()\nclass LoggerMiddleware extends BaseMiddleware {\n    @inject(TYPES.Logger) private readonly _logger: Logger;\n    public handler(\n        req: express.Request,\n        res: express.Response,\n        next: express.NextFunction\n    ) {\n        if (this.httpContext.user.isAuthenticated()) {\n            this._logger.info(`${this.httpContext.user.details.email} =\u003e ${req.url}`);\n        } else {\n            this._logger.info(`Anonymous =\u003e ${req.url}`);\n        }\n        next();\n    }\n}\n```\n\nWe also need to declare some type bindings:\n\n```ts\nconst container = new Container();\n\ncontainer.bind\u003cLogger\u003e(TYPES.Logger)\n        .to(Logger);\n\ncontainer.bind\u003cLoggerMiddleware\u003e(TYPES.LoggerMiddleware)\n         .to(LoggerMiddleware);\n\n```\n\nWe can then inject `TYPES.LoggerMiddleware` into one of our controllers.\n\n```ts\n@controller(\"/\")\nclass UserDetailsController extends BaseHttpController {\n\n    @inject(\"AuthService\") private readonly _authService: AuthService;\n\n    @httpGet(\"/\", TYPES.LoggerMiddleware)\n    public async getUserDetails() {\n        if (this.httpContext.user.isAuthenticated()) {\n            return this._authService.getUserDetails(this.httpContext.user.details.id);\n        } else {\n            throw new Error();\n        }\n    }\n}\n```\n\n### Request-scope services\n\nMiddleware extending `BaseMiddleware` is capable of re-binding services in the scope of a HTTP request.\nThis is useful if you need access to a HTTP request or context-specific property in a service that doesn't have\nthe direct access to them otherwise.\n\nConsider the below `TracingMiddleware`. In this example we want to capture the `X-Trace-Id` header from the incoming request\nand make it available to our IoC services as `TYPES.TraceIdValue`:\n\n```typescript\nimport { inject, injectable } from \"inversify\";\nimport { BaseHttpController, BaseMiddleware, controller, httpGet } from \"inversify-express-utils\";\nimport * as express from \"express\";\n\nconst TYPES = {\n    TraceId: Symbol.for(\"TraceIdValue\"),\n    TracingMiddleware: Symbol.for(\"TracingMiddleware\"),\n    Service: Symbol.for(\"Service\"),\n};\n\n@injectable()\nclass TracingMiddleware extends BaseMiddleware {\n\n    public handler(\n        req: express.Request,\n        res: express.Response,\n        next: express.NextFunction\n    ) {\n        this.bind\u003cstring\u003e(TYPES.TraceIdValue)\n            .toConstantValue(`${ req.header('X-Trace-Id') }`);\n\n        next();\n    }\n}\n\n@controller(\"/\")\nclass TracingTestController extends BaseHttpController {\n\n    constructor(@inject(TYPES.Service) private readonly service: Service) {\n        super();\n    }\n\n    @httpGet(\n        \"/\",\n        TYPES.TracingMiddleware\n    )\n    public getTest() {\n        return this.service.doSomethingThatRequiresTheTraceID();\n    }\n}\n\n@injectable()\nclass Service {\n    constructor(@inject(TYPES.TraceIdValue) private readonly traceID: string) {\n    }\n\n    public doSomethingThatRequiresTheTraceID() {\n        // ...\n    }\n}\n```\n\nThe `BaseMiddleware.bind()` method will bind the `TYPES.TraceIdValue` if it hasn't been bound yet or re-bind if it has\nalready been bound.\n\n### Middleware decorators\nYou can use the `@withMiddleware()` decorator to register middleware on controllers and handlers. For example: \n```typescript\nfunction authenticate() {\n    return withMiddleware(\n        (req, res, next) =\u003e {\n            if (req.user === undefined) {\n                res.status(401).json({ errors: [ 'You must be logged in to access this resource.' ] })\n            }\n            next()\n        }\n    )\n}\n\nfunction authorizeRole(role: string) {\n    return withMiddleware(\n        (req, res, next) =\u003e {\n            if (!req.user.roles.includes(role)) {\n                res.status(403).json({ errors: [ 'Get out.' ] })\n            }\n            next()\n         }\n    )\n}\n\n@controller('/api/user')\n@authenticate()\nclass UserController {\n\n    @httpGet('/admin/:id')\n    @authorizeRole('ADMIN')\n    public getById(@requestParam('id') id: string) {\n        ...\n    }\n}\n```\nYou can also decorate controllers and handlers with middleware using BaseMiddleware identitifers: \n```typescript\nclass AuthenticationMiddleware extends BaseMiddleware {\n    handler(req, res, next) {\n        if (req.user === undefined) {\n            res.status(401).json({ errors: [ 'User is not logged in.' ] })\n        }\n    }\n}\n\ncontainer.bind\u003cBaseMiddleware\u003e(\"AuthMiddleware\").to(AuthenticationMiddleware)\n\n@controller('/api/users')\n@withMiddleware(\"AuthMiddleware\")\nclass UserController {\n    ...\n}\n```\n\n## Route Map\n\nIf we have some controllers like for example:\n\n```ts\n@controller(\"/api/user\")\nclass UserController extends BaseHttpController {\n    @httpGet(\"/\")\n    public get() {\n        return {};\n    }\n    @httpPost(\"/\")\n    public post() {\n        return {};\n    }\n    @httpDelete(\"/:id\")\n    public delete(@requestParam(\"id\") id: string) {\n        return {};\n    }\n}\n\n@controller(\"/api/order\")\nclass OrderController extends BaseHttpController {\n    @httpGet(\"/\")\n    public get() {\n        return {};\n    }\n    @httpPost(\"/\")\n    public post() {\n        return {};\n    }\n    @httpDelete(\"/:id\")\n    public delete(@requestParam(\"id\") id: string) {\n        return {};\n    }\n}\n```\n\nWe can use the `prettyjson` function to see all the available enpoints:\n\n```ts\nimport { getRouteInfo } from \"inversify-express-utils\";\nimport * as prettyjson from \"prettyjson\";\n\n// ...\n\nlet server = new InversifyExpressServer(container);\nlet app = server.build();\nconst routeInfo = getRouteInfo(container);\n\nconsole.log(prettyjson.render({ routes: routeInfo }));\n\n// ...\n```\n\n\u003e :warning: Please ensure that you invoke `getRouteInfo` after invoking `server.build()`!\n\nThe output formatter by `prettyjson` looks as follows:\n\n```txt\nroutes:\n  -\n    controller: OrderController\n    endpoints:\n      -\n        route: GET /api/order/\n      -\n        route: POST /api/order/\n      -\n        path: DELETE /api/order/:id\n        route:\n          - @requestParam id\n  -\n    controller: UserController\n    endpoints:\n      -\n        route: GET /api/user/\n      -\n        route: POST /api/user/\n      -\n        route: DELETE /api/user/:id\n        args:\n          - @requestParam id\n```\n\n## Examples\n\nSome examples can be found at the [inversify-express-example](https://github.com/inversify/inversify-express-example) repository.\n\n## License\n\nLicense under the MIT License (MIT)\n\nCopyright © 2016-2017 [Cody Simms](https://github.com/codyjs)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finversify%2Finversify-express-utils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Finversify%2Finversify-express-utils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finversify%2Finversify-express-utils/lists"}