# koa-controller

> Middleware for Koa which handles the routing of your application were related functionalities are splitted into routes, controllers and constraints.

Latest version **1.1.0** (published 2014-09-11) · MIT license · 0 weekly downloads

## Install

```sh
npm install koa-controller
pnpm add koa-controller
yarn add koa-controller
bun add koa-controller
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.0 |
| Published | 2014-09-11 |
| First published | 2014-08-16 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Node | >= 0.11.9 |
| Dependencies | 4 |
| Known vulnerabilities | 0 (+5 in 1 direct dependencies) |
| Install scripts | no |
| GitHub stars | 17 |
| Author | xpepermint |
| Maintainers | xpepermint |
| Keywords | koa, controller, controllers, constraint, constraints, policy, policies, route, routes, routing, router, mvc, rest, rails |

## Links

- npm: https://www.npmjs.com/package/koa-controller
- Repository: https://github.com/xpepermint/koa-controller
- Issues: https://github.com/xpepermint/koa-controller/issues
- npm.io page: https://npm.io/package/koa-controller

## Dependencies (4)

- [lodash](https://npm.io/package/lodash.md) ^2.4.1
- [co-body](https://npm.io/package/co-body.md) ^1.0.0
- [koa-route](https://npm.io/package/koa-route.md) ^2.1.0
- [koa-compose](https://npm.io/package/koa-compose.md) ^2.3.0

## Alternatives

- [express-promise-router](https://npm.io/package/express-promise-router.md) — 736.1K weekly downloads
- [next-usequerystate](https://npm.io/package/next-usequerystate.md) — 29.8K weekly downloads
- [@bitkyc08/opencodex](https://npm.io/package/@bitkyc08/opencodex.md) — 4.6K weekly downloads
- [lynkr](https://npm.io/package/lynkr.md) — 575 weekly downloads
- [baremetal.js](https://npm.io/package/baremetal.js.md) — 42 weekly downloads

## Recent versions

- 1.1.0 (latest) — 2014-09-11
- 1.0.1 — 2014-09-10
- 1.0.0 — 2014-09-10
- 0.0.8 — 2014-08-29
- 0.0.7 — 2014-08-29
- 0.0.6 — 2014-08-28
- 0.0.5 — 2014-08-17
- 0.0.4 — 2014-08-17
- 0.0.3 — 2014-08-17
- 0.0.2 — 2014-08-17
- 0.0.1 — 2014-08-16

## README

# [koa](http://koajs.com/)-controller

![Build Status](https://travis-ci.org/xpepermint/koa-controller.svg?branch=master)&nbsp;[![NPM version](https://badge.fury.io/js/koa-controller.svg)](http://badge.fury.io/js/koa-controller)&nbsp;[![Dependency Status](https://gemnasium.com/xpepermint/koa-controller.svg)](https://gemnasium.com/xpepermint/koa-controller)

`Koa-controller` in a middleware for `Koa` which handles the routing of your application where related functionalities are splitted into `routes`, `controllers` and `constraints`. The module is built on top of [koa-route](https://github.com/koajs/route) middleware. It optimizes your code and brings the following features into your project:
- Flexible `routes` handler with a single point of router configuration.
- Application `controllers` for handling application responses.
- Access control middleware with `constraints` for limiting requests to application controllers, handling user authentication and security.
- Context tools for easy dynamic data manipulation.

## Installation

Install the [npm](https://www.npmjs.org/package/koa-controller) package.

```
npm install koa-controller --save
```

Attach the middleware.

```js
var koa = require('koa');
var app = koa();
var kc = require('koa-controller');
app.use(kc.tools()); // optional
app.use(kc.router());
app.listen(3000);
```

By default the middleware expects that controllers exist at `app/controllers/{controller}.js`, constraints at `app/constraints/{constraint}.js` and the router configuration file at `config/routes.js`. We can easily change the default behavior as shown bellow.

```js
app.use(controller({
  routesPath: 'my/path/routes.js',
  controllerPath: 'my/controllers/{controller}.js', // note that {controller} is a variable
  constraintPath: 'my/constraints/{constraint}.js', // note that {constraint} is a variable
  logger: console.log // custom logger function
}));
```

Note that `routesPath` and `controllerPath` must exist where `constraintPath` is not required.

## Routes

Routes file is a simple key-value object where the `key` represents a `route` and the `value` represents a `task`. Create a new file and define your project's routes based on the example bellow.

```js
// config/routes.js
module.exports = {

  // controller#action
  '/users/:id?': { to: 'users#find' },
  'post /users': { to: 'users#create' },
  'put|post /users/:id': { to: 'users#update' },
  'get /users/:id/words/:slug*': { to: 'events#words' },
  'get /event/:slug+': { to: 'events#index', constraint: 'api#ip' },

  // redirections
  'get /to/google': { to: 'http://www.google.com' },
  'get /to/home': { to: '/' },

  // using a function
  'get /events/:id': { to: function *(id) { this.body = ... } },

  ...
};
```

You check [koa-route](https://github.com/koajs/route) and [path-to-regexp](https://github.com/component/path-to-regexp) for more information.

## Controller

Controller is a simple key-value object where the `key` represents the name of an `action` and the `value` represents a generator function that processes the request. Create a new file for your first controller and define actions based on the example bellow. Don't forget to connect the new controller with a route inside `routes.js` file.

```js
// app/controllers/users.js
module.exports = {

  find: function*() {
    this.body = ...;
  },

  update: function*(id) {
  },

  words: function*(id, slug) {
  },

  ...
};
```

Notice the `this.body` call? Every `action` inside a controller has access to [Koa context](http://koajs.com/#context). Check [koa-route](https://github.com/koajs/route) for details.

## Constraint

Constraint is a simple key-value object where the `key` represents the name of a constraint and the `value` represents a generator function that processes the request. Create a new file for your first constraint and define constraints based on the example bellow. Don't forget to connect the new constraint with a route inside `routes.js` file.

```js
// app/constraints/api.js
module.exports = {

  ip: function*(next) {
    if (this.request.ip == '192.168.1.100') { // allow access only from this IP address
      yield next;
    } else {
      this.body = 'Unauthorized IP address';
      this.status = 401;
    }
  },

  ...
};
```

Note that constraints are very much like controllers thus every constraint action has access to [Koa context](http://koajs.com/#context). Check [koa-route](https://github.com/koajs/route) for details.

## Tools

By attaching `kc.tools()` middleware the context features are extended.

### ctx.form([names])

Type: `Function`
Returns: `Object`

Parsed request body data. You can retrive only selected attributes by specifying a list of `names`.

```js
console.log( _.form() );
// -> { 'name': 'John', 'email': 'john@gmail.com', 'age': 33 }
console.log( _.form('name', 'age') );
// -> { 'name': 'John', 'age': 33 }
```

---
_Source: https://npm.io/package/koa-controller · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
