# ksc-mocker

## koa 模拟接口服务 , 基于 koa , [mockjs](mockjs.com)

## install

```
npm install -D ksc-mocker
```

## uninstall

```
npm uninstall ksc-mocker
```

## usage

shell

```
 $> kmock -h

    Usage: kmock [options]

    Options:

      -V, --version        output the version number
      -S, --src [src]      glob模式使用引号包裹 , 逗号分隔 , 默认为 ./mock/**/*.js,!./node_modules/**/* (default: ./mock/**/*.js,!./node_modules/**/*)
      -W, --watch [watch]  设置监控文件改动 , 默认为 false (default: true)
      -P, --port [port]    设置启动端口 , 默认为 3500 (default: 3500)
      -H, --host [host]    这是启动host , 默认为 127.0.0.1 (default: 127.0.0.1)
      -h, --help           output usage information

```

例子

```bash
kmock -h
kmock -S "./test/**/*.js" -W
```

配置文件说明

* JS 版

```js
module.exports = [
    {
        path:"/kceapi",
        when:(request)=>{
            return true
        },
        method:'all' //默认get , `all`为特殊值,代表全部支持
        proxy:{
            target: 'https://kce.console.ksyun.com',
            secure: false
        } //proxy `http-proxy-middleware` 设置方法
    },
    {
        path:"/kceapi",
        when:({query})=>{
            return query.Action == 'QueryClusterSimpleList'
        },
        method:'get' //默认get , `all`为特殊值,代表全部支持
        response: {
            "RequestId": "188e4dc7-8632-4a87-a0d5-8b55c2d93ee3",
            "Data": {
                "ClusterList": [{
                    "ClusterId": "33ssxc444",
                    "ClusterName": "集群1",
                }]
            }
        }
    }
];
```

* json 版本

```
[
    {
        "path":"/faker222",
        "response": {
            "array|1-10": ["Mock.js"],
            "foo": "Syntax Dem222",
            "nested": {
                "a": {
                    "b": {
                        "c": "Mock.js"
                    }
                }
            },
            "absolutePath": "@/foo @/nested/a/b/c"
        }
    }
]
```

### 匹配规则
1. 优先根据 `path` 全路径匹配或模糊路径匹配 、`method` 请求方法 ,匹配出有效命中集合
2. 通过 `when` 函数判断最后的命中规则项目 , 作为命中规则 默认 `when` 全部返回生效
4. 规则命中后如是`proxy`则代理到指定的服务 ， 如是`response`则 `mock` 数据返回

path > path-to-regexp | when  > last | (proxy ? proxy : mock)

### 书写配置方法
* `path`、`method`必填
* `when`选填，接受`request`和`ctx`两个参数，根据返回结果匹配命中规则
* `proxy`选填，语法参照`http-proxy-middleware`
* `response`返回结果，需自己mock数据时理论上必填，（当配置proxy时，将代理到指定服务器，response参数不写）
* 当命中规则项目有很多时，返回第一个成功匹配的数据（因此，第一条数据习惯性可配置为全局性的proxy，其余数据按需求写mock）

### run

```
查看 package.json
```