Circe
A framework based on Koa v2.
基于Koa v2的开发框架。
关于发音
英语:Circe[ˈsə:si]
中文:瑟茜[sè xī]
一、安装
$ npm install circe --save
二、入门
基于Koa2
开发,保留与之相同的用法,所有api和中间件均兼容
const Koa = require('koa')
const app = new Koa()
app.use()
app.listen(8080. function () {})
const Circe = require('circe')
const circe = new Circe()
circe.use()
circe.listen(8080. function () {})
Koa实例对象的属性都有(具体的作用请查看Koa官方文档):
- use
- toJSON
- inspect
- on
- proxy
- middleware
- subdomainOffset
- env
- context
- request
- response
- keys
三、进阶
1. 可获得Koa实例和http server实例
const Circe = require('circe')
const circe = new Circe()
console.log(circe.app)
console.log(circe.server)
2. 更多的实例方法
circe.route(Router) 注册路由,传入路由对象
const Circe = require('circe')
const router = new Circe.Router()
router.get('/user', async () => { })
router.post('/user', async () => { })
circe.route(router)
circe.route(String) 注册路由,传入路由目录
const Circe = require('circe')
const router = new Circe.Router()
router.get('/user', async () => { })
router.post('/user', async () => { })
module.exports = router
const path = require('path')
const Circe = require('circe')
circe.route(path.resolve(__dirname, 'apis'))
circe.inject(key, value) 注入内容到context,传入键和值参数
const Circe = require('circe')
const circe = new Circe()
circe.inject('$hello', function () { console.log('hello') })
circe.inject('$a.b', 'test' })
circe.inject('foo.bar', {a: 1, b: 2})
circe.use(asynct (ctx, next) => {
ctx.$hello()
ctx.$a.b
ctx.foo.bar.a
ctx.foo.bar.b
})
circe.inject(object) 注入内容到context,传入对象和前缀
const Circe = require('circe')
const circe = new Circe()
circe.inject({a: 1, b: 2})
circe.inject({$c: 3, $d: 4})
circe.use(asynct (ctx, next) => {
ctx.a
ctx.b
ctx.$c
ctx.$d
})
3. 内置中间件全家桶
内置的中间件全都绑定在Circe
类上,不需要再去npm或github上需找和对比需要的中间件,更多的中间件正在丰富中。
4. 拓展的context
除了koa自带的context方法和属性,circe对context进行了拓展:
5. 实用工具库
config 配置文件管理
const Circe = require('circe')
const config = Circe.config.from(__dirname + '/config')
示例1:
- config
- default.js
- development.js
- production.js
如有以上目录结构,且当前运行环境为development
,将会整合default.js
和development.js
作为导出对象。
示例2
- config
- default
- development
- production
如有以上目录结构,且当前运行环境为production
,将会整合default
、production
目录下所有文件作为导出对象。
导出对象结构为:
{
app: {...},
db: {...},
other: {...}
}
6. 支持typescript
已添加对typescript
的声明,详情请看index.d.ts
import * as Circe from 'circe'
const circe = new Circe()
模板项目
circe-template - circe + babel
circe-template-ts - circe + typescript