# cc-router

> Hapi-like configurable router in express

Latest version **4.0.0** (published 2017-10-21) · MIT license · 0 weekly downloads

## Install

```sh
npm install cc-router
pnpm add cc-router
yarn add cc-router
bun add cc-router
```

## 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 | 4.0.0 |
| Published | 2017-10-21 |
| First published | 2017-04-27 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 2 |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | Nattadej Waiyatharee |
| Maintainers | chomchob |
| Keywords | express, router |

## Links

- npm: https://www.npmjs.com/package/cc-router
- Repository: https://github.com/ChomCHOB/cc-router
- Homepage: https://github.com/ChomCHOB/cc-router#readme
- Issues: https://github.com/ChomCHOB/cc-router/issues
- npm.io page: https://npm.io/package/cc-router

## Dependencies (2)

- [debug](https://npm.io/package/debug.md) ^3.1.0
- [express](https://npm.io/package/express.md) ^4.16.2

## 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

- 4.0.0 (latest) — 2017-10-21
- 2.0.0 — 2017-04-27

## README

### cc-router
> Configurable router in express.js (hapi.js route style)

**How to install**
```
npm install --save cc-router
```

**How to use**
> [index.js](example/index.js)
```js
const express = require('express')   // express app 
const router = require('cc-router')

const app = express()
const rootDir = __dirname
const routesDir = 'routes'
router(app, rootDir, routesDir)

// or with middlewares
const middlewarerDir = 'middlewares'  // optional
router(app, rootDir, routesDir, middlewarerDir)
```

Project structure example
```
base
 |- middlewares
 |   |- auth-middleware.js
 |- routes
 |   |- index.js
 |   |- v1
 |      |- user.js
 |- index.js
```

### Route config
**Required**
- `method`: Http request method ex. GET, POST, PUT, DELETE
- `path`: Path to this endpoint
- `handler`: Function for this route endpoint

**Optional**
- `configs`: Add middlewares to this route
- `x`: fast disable route
- `env`: enabled route when NODE_ENV is matched

#### Example route file
> [routes/index.js](example/routes/index.js)
```js
module.exports = [
  {
    method: 'GET',
    path: '/',
    handler: (req, res) => (res.json({msg: 'hello from v1.0'}))
  },
  {
    method: 'POST',
    path: '/hello',
    handler: (req, res) => {
      res.json({msg: 'world'});
    }
  },
  {
    method: 'GET',
    path: '/disable',
    x: true,
    handler: (req, res) => res.send('pong')
  },
  {
    method: 'GET',
    path: '/ping',
    env: ['production', 'develop'], // allow when NODE_ENV is `production` or `develop`
    handler: (req, res) => res.send('pong')
  },
  // middleware example
  {
    method: 'post',
    path: '/test-validate',
    configs: {
      validate: {
        body: {
          id: Joi.string().required()
        }
      }
    },
    handler: (req, res) => {
      res.json({
        msg: 'success',
        id: req.body.id
      })
    }
  }
]
```

### Example middleware
> [routes/index.js](example/routes/index.js)
```js
const Joi = require('joi')

module.exports = [
  {
    method: 'post',
    path: '/test-validate',
    configs: {                  // middleware configs
      validate: {               // `validate` middleware
        body: {
          id: Joi.string().required()
        }
      }
    },
    handler: (req, res) => {
      res.json({
        msg: 'success',
        id: req.body.id
      })
    }
  }
]
```
> [middlewares/input-validate.js](example/middlewares/input-validate.js)
```js
const validator = require('express-validation')

module.exports.keyName = 'validate'

module.exports.init = (router, {path, method, configs}) => {
  const keyName = module.exports.keyName
  // check configs match with `validate`
  if (configs && keyName in configs && typeof configs[keyName] === 'object') {
    router[method](path, validator(configs[keyName]))
    return true
  }
}
```

#### Try an example
```sh
# clone project
git clone https://github.com/ChomCHOB/cc-router.git && cd cc-router

# install dependencies
npm install

# run an example
npm run example

## try to request 
# simple get
curl -X GET http://127.0.0.1:3000/hello
# {
#   "msg": "hello world"
# }

# error POST (no id)
curl -X POST http://127.0.0.1:3000/test-validate
# {                              
#   "status": 400,               
#   "statusText": "Bad Request", 
#   "errors": [                  
#     {                          
#       "field": [               
#         "id"                   
#       ],                       
#       "location": "body",      
#       "messages": [            
#         "\"id\" is required"   
#       ],                       
#       "types": [               
#         "any.required"         
#       ]                        
#     }                          
#   ]                            
# }                              

# success POST with id
curl -X POST http://127.0.0.1:3000/test-validate \
  -H 'content-type: application/json' \
  -d '{"id": "1234"}'
# {
#   "msg": "success",
#   "id": "1234"
# }
```

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