{"id":19834163,"url":"https://github.com/diego-d5000/inversify-koa-utils","last_synced_at":"2025-06-14T20:15:05.385Z","repository":{"id":57275518,"uuid":"98457931","full_name":"diego-d5000/inversify-koa-utils","owner":"diego-d5000","description":"inversify-koa-utils is a module based on inversify-express-utils. This module has utilities for koa 2 applications development using decorators and IoC Dependency Injection (with inversify)","archived":false,"fork":false,"pushed_at":"2022-01-13T02:38:31.000Z","size":46,"stargazers_count":30,"open_issues_count":4,"forks_count":14,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-05-01T17:31:45.806Z","etag":null,"topics":["dependency-injection","inversify","inversion-of-control","javascript","koa","koa2","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/diego-d5000.png","metadata":{"files":{"readme":"README.md","changelog":null,"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}},"created_at":"2017-07-26T19:20:29.000Z","updated_at":"2024-02-29T00:04:28.000Z","dependencies_parsed_at":"2022-09-16T11:13:01.334Z","dependency_job_id":null,"html_url":"https://github.com/diego-d5000/inversify-koa-utils","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/diego-d5000/inversify-koa-utils","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diego-d5000%2Finversify-koa-utils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diego-d5000%2Finversify-koa-utils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diego-d5000%2Finversify-koa-utils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diego-d5000%2Finversify-koa-utils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/diego-d5000","download_url":"https://codeload.github.com/diego-d5000/inversify-koa-utils/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/diego-d5000%2Finversify-koa-utils/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259877038,"owners_count":22925399,"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","inversify","inversion-of-control","javascript","koa","koa2","typescript"],"created_at":"2024-11-12T12:03:26.705Z","updated_at":"2025-06-14T20:15:05.348Z","avatar_url":"https://github.com/diego-d5000.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# inversify-koa-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/diego-d5000/inversify-koa-utils.svg?branch=master)](https://travis-ci.org/diego-d5000/inversify-koa-utils)\n[![Test Coverage](https://codeclimate.com/github/diego-d5000/inversify-koa-utils/badges/coverage.svg)](https://codeclimate.com/github/diego-d5000/inversify-koa-utils/coverage)\n[![npm version](https://badge.fury.io/js/inversify-koa-utils.svg)](http://badge.fury.io/js/inversify-koa-utils)\n[![Dependencies](https://david-dm.org/diego-d5000/inversify-koa-utils.svg)](https://david-dm.org/diego-d5000/inversify-koa-utils#info=dependencies)\n[![img](https://david-dm.org/diego-d5000/inversify-koa-utils/dev-status.svg)](https://david-dm.org/diego-d5000/inversify-koa-utils/#info=devDependencies)\n[![img](https://david-dm.org/diego-d5000/inversify-koa-utils/peer-status.svg)](https://david-dm.org/diego-d5000/inversify-koa-utils/#info=peerDependenciess)\n[![Known Vulnerabilities](https://snyk.io/test/github/diego-d5000/inversify-koa-utils/badge.svg)](https://snyk.io/test/github/diego-d5000/inversify-koa-utils)\n\n[![NPM](https://nodei.co/npm/inversify-koa-utils.png?downloads=true\u0026downloadRank=true)](https://nodei.co/npm/inversify-koa-utils/)\n[![NPM](https://nodei.co/npm-dl/inversify-koa-utils.png?months=9\u0026height=3)](https://nodei.co/npm/inversify-koa-utils/)\n\ninversify-koa-utils is a module based on [inversify-express-utils](https://github.com/inversify/inversify-express-utils). This module has utilities for koa 2 applications development using decorators and IoC Dependency Injection (with inversify)\n\n## Installation\nYou can install `inversify-koa-utils` using npm:\n\n```\n$ npm install inversify inversify-koa-utils reflect-metadata --save\n```\n\nThe `inversify-koa-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\nTo use a class as a \"controller\" for your koa app, simply add the `@controller` decorator to the class. Similarly, decorate methods of the class to serve as request handlers.\nThe following example will declare a controller that responds to `GET /foo'.\n\n```ts\nimport * as Koa from 'koa';\nimport { interfaces, Controller, Get, Post, Delete } from 'inversify-koa-utils';\nimport { injectable, inject } from 'inversify';\n\n@controller('/foo')\n@injectable()\nexport class FooController implements interfaces.Controller {\n\n    constructor( @inject('FooService') private fooService: FooService ) {}\n\n    @httpGet('/')\n    private index(ctx: Router.IRouterContext , next: () =\u003e Promise\u003cany\u003e): string {\n        return this.fooService.get(ctx.query.id);\n    }\n\n    @httpGet('/basickoacascading')\n    private koacascadingA(ctx: Router.IRouterContext, nextFunc: () =\u003e Promise\u003cany\u003e): string {\n        const start = new Date();\n        await nextFunc();\n        const ms = new Date().valueOf() - start.valueOf();\n        ctx.set(\"X-Response-Time\", `${ms}ms`);\n    }\n\n    @httpGet('/basickoacascading')\n    private koacascadingB(ctx: Router.IRouterContext , next: () =\u003e Promise\u003cany\u003e): string {\n        ctx.body = \"Hello World\";\n    }\n\n    @httpGet('/')\n    private list(@queryParams('start') start: number, @queryParams('count') cound: number): string {\n        return this.fooService.get(start, count);\n    }\n\n    @httpPost('/')\n    private async create(@response() res: Koa.Response) {\n        try {\n            await this.fooService.create(req.body)\n            res.body = 201\n        } catch (err) {\n            res.status = 400 \n            res.body = { error: err.message }\n        }\n    }\n\n    @httpDelete('/:id')\n    private delete(@requestParam(\"id\") id: string, @response() res: Koa.Response): Promise\u003cvoid\u003e {\n        return this.fooService.delete(id)\n            .then(() =\u003e res.body = 204)\n            .catch((err) =\u003e {\n                res.status = 400\n                res.body = { error: err.message }\n            })\n    }\n}\n```\n\n### Step 2: Configure container and server\nConfigure the inversify container in your composition root as usual.\n\nThen, pass the container to the InversifyKoaServer constructor. This will allow it to register all controllers and their dependencies from your container and attach them to the koa app.\nThen just call server.build() to prepare your app.\n\nIn order for the InversifyKoaServer 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-koa-utils is empty and solely for convenience, so feel free to implement your own if you want.\n\n```ts\nimport * as bodyParser from 'koa-bodyparser';\n\nimport { Container } from 'inversify';\nimport { interfaces, InversifyKoaServer, TYPE } from 'inversify-koa-utils';\n\n// set up container\nlet container = new Container();\n\n// note that you *must* bind your controllers to Controller\ncontainer.bind\u003cinterfaces.Controller\u003e(TYPE.Controller).to(FooController).whenTargetNamed('FooController');\ncontainer.bind\u003cFooService\u003e('FooService').to(FooService);\n\n// create server\nlet server = new InversifyKoaServer(container);\nserver.setConfig((app) =\u003e {\n  // add body parser\n  app.use(bodyParser());\n});\n\nlet app = server.build();\napp.listen(3000);\n```\n\n## InversifyKoaServer\nA wrapper for an koa Application.\n\n### `.setConfig(configFn)`\nOptional - exposes the koa application object for convenient loading of server-level middleware.\n\n```ts\nimport * as morgan from 'koa-morgan';\n// ...\nlet server = new InversifyKoaServer(container);\n\nserver.setConfig((app) =\u003e {\n    var logger = morgan('combined')\n    app.use(logger);\n});\n```\n\n### `.setErrorConfig(errorConfigFn)`\nOptional - like `.setConfig()`, except this function is applied after registering all app middleware and controller routes.\n\n```ts\nlet server = new InversifyKoaServer(container);\nserver.setErrorConfig((app) =\u003e {\n    app.use((ctx, next) =\u003e {\n        console.error(err.stack);\n        ctx.status = 500\n        ctx.body = 'Something broke!';\n    });\n});\n```\n\n### `.build()`\nAttaches all registered controllers and middleware to the koa application. Returns the application instance.\n\n```ts\n// ...\nlet server = new InversifyKoaServer(container);\nserver\n    .setConfig(configFn)\n    .setErrorConfig(errorConfigFn)\n    .build()\n    .listen(3000, 'localhost', callback);\n```\n\n## Using a custom Router\nIt is possible to pass a custom `Router` instance to `InversifyKoaServer`:\n\n```ts\n\nimport * as Router from 'koa-router';\n\nlet container = new Container();\n\nlet router = new Router({\n    prefix: '/api',\n});\n\nlet server = new InversifyKoaServer(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`InversifyKoaServer`\n\n```ts\nlet container = new Container();\n\nlet server = new InversifyKoaServer(container, null, { rootPath: \"/api/v1\" });\n```\n\n## Using a custom koa application\nIt is possible to pass a custom `koa.Application` instance to `InversifyKoaServer`:\n\n```ts\nlet container = new Container();\n\nlet app = new Koa();\n//Do stuff with app\n\nlet server = new InversifyKoaServer(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 koa 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`, and `@All`. For anything more obscure, use `@httpMethod` (Or make a PR :smile:).\n\n### `@request()`\nBinds a method parameter to the request object.\n\n### `@response()`\nBinds a method parameter to the response object.\n\n### `@requestParam(name?: string)`\nBinds a method parameter to request.params object or to a specific parameter if a name is passed.\n\n### `@queryParam(name?: string)`\nBinds a method parameter to request.query or to a specific query parameter if a name is passed.\n\n### `@requestBody(name?: string)`\nBinds a method parameter to request.body or to a specific body property if a name is passed. If the bodyParser middleware is not used on the koa app, this will bind the method parameter to the koa request object.\n\n### `@requestHeaders(name?: string)`\nBinds a method parameter to the request headers.\n\n### `@cookies()`\nBinds a method parameter to the request cookies.\n\n### `@next()`\nBinds a method parameter to the next() function.\n\n## License\n\nLicense under the MIT License (MIT)\n\nCopyright © 2017 [Diego Plascencia](https://github.com/diego-d5000)\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","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdiego-d5000%2Finversify-koa-utils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdiego-d5000%2Finversify-koa-utils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdiego-d5000%2Finversify-koa-utils/lists"}