heirloom-api-plugin
基于heirloom-corePlugin接口,对koa-router^7.1.1的封装实现。
遵循规约重于配置的思想,扫描指定文件目录下的JS文件,按照文件目录层级自动映射成为路由。
e.g:
project/api/v1/sample.js
->http://domain.com/api/v1/sample
;project/api/v1/sample/index.js
->http://domain.com/api/v1/sample
;project/api/index.js
->http://domain.com/api
;
相关项目
快速开始
执行以下命令新建工程目录:example/
mkdir example && cd example && npm init
进入example/
目录,执行以下命令安装依赖:
npm install heirloom-core heirloom-api-plugin --save
编写example/index.js
:
const NormalServer = NormalServer;const KoaEngine = KoaEngine;const HeirloomAPIPlugin = HeirloomAPIPlugin; const server = logger: console port: 4000 engine: KoaEngine; server; serverstart;
编写example/api/sample.js
文件,实现用于生产环境的API:
// GET请求exports { ctxbody = 'production';};
编写example/api/__mocks__/sample.js
文件,Mock接口:
// GET请求exports { ctxbody = 'staging';};
在example/
目录,执行以下命令启动服务:
node .
另起一个终端访问:
curl http://localhost:4000/api/sample # 返回:staging
结束之前启动的进程,加上环境变量NODE_ENV
再次启动服务:
NODE_ENV=production node .
另起一个终端访问:
curl http://localhost:4000/api/sample # 返回:production
类型定义
// HTTP Methodsdeclare type Heirloom$AllowedMethod = $Enum< get: string post: string update: string patch: string delete: string put: string >; // Controller, 单个或多个Function,多个Function时详见:https://github.com/alexmingoia/koa-router#multiple-middlewaredeclare type Heirloom$Controller = Function | Array<Function>; // API.jsdeclare type Heirloom$API = key: Heirloom$AllowedMethod: Heirloom$Controller ; // HeirloomAPIPlugin类构造参数declare type Heirloom$APIPluginOptions = mock: boolean // 是否启用mock,缺省(默认)为:process.env.NODE_ENV !== 'production',即在NODE_ENV环境变量值为`production`时关闭mock。 scanDirectory: string // 扫描目录,缺省(默认)为:api/ apiRoot: string // 路由前缀,缺省(默认)为:/api,即:http://domain.com/api/path/to/something,如有需要可指定为:/,即:http://domain.com/path/to/something; // HeirloomAPIPlugin类declare : HeirloomAPIPlugin;}
Heirloom$API
实现其他类型的请求的接口
根据example/api/sample.js
:
// POST api/sampleexports { ctxbody = 'post';}; // PATCH api/sampleexports { ctxbody = 'patch';}; // DELETE api/sampleexports { ctxbody = 'post';}; // update、put...略
路径参数(Path Variables)
example/api/sample.js
:
// GET: api/sample/1 { ctxbody = id: ctxparamsid ; // { id: 1 }} getparams = ':id'; exportsget = get;
ES6 Class
; async { const username = ctxqueryusername; const response = await ; if responseok ctxbody = await response; else const text = await responsetext; throw text; } async { } moduleexports = ;
Mock
正式环境 | Mock | 请求 |
---|---|---|
/api/v1/sample/index.js |
/api/v1/sample/__mocks__/index.js |
http://domain.com/api/v1/sample |
/api/v1/sample.js |
/api/v1/__mocks__/sample.js |
http://domain.com/api/v1/sample |