whistle.savemock
v1.0.3
Published
Whistle插件,支持自动抓取数据并Mock.
Readme
whistle.savemock
Whistle插件,支持自动抓取数据并Mock.
安装
npm install whistle.savemock使用
自动保存并Mock
# 简写配置
https://blog.alanwei.com savemock://D:\temporary\mock\whistle\t2
# 以上简写配置对应的完整配置如下
https://blog.alanwei.com/ savemock://{mock.json}
```mock.json
{
"mode": "auto",
"directory": "D:\\temporary\\mock\\whistle\\t2",
"types": ["json"],
"storage": "hash",
"responseHeaders": "^(access-|x-)|^(cache-control|content-type)$"
}
```注意,对于Windows系统,简写模式下,目录路径不需要双斜线,但是完整配置(JSON格式)时需要使用双斜线。
仅抓取或仅Mock数据
# 抓取的简写配置
https://blog.alanwei.com savemock://save@/data/mock/whistle
# 以上简写配置对应的完整配置如下
https://blog.alanwei.com/ savemock://{config.json}
```config.json
{
"mode": "save",
"directory": "/data/mock/whistle",
"types": ["json"],
"storage": "hash",
"responseHeaders": "^(access-|x-)|^(cache-control|content-type)$"
}
```
# Mock的简写配置
https://blog.alanwei.com savemock://mock@/data/mock/whistle
# 以上简写配置对应的完整配置如下
https://blog.alanwei.com/ savemock://{config.json}
```config.json
{
"mode": "mock",
"directory": "/data/mock/whistle",
"types": ["json"],
"storage": "hash",
"responseHeaders": "^(access-|x-)|^(cache-control|content-type)$"
}
```配置说明
完整配置对应的TypeScript类型如下:
type SaveMockConfiguration = {
/**
* 设置工作模式
*
* * `auto` 表示自动模式,如果存在mock数据,则返回mock数据,不存在则保存数据
* * `save` 仅抓取保存数据,不进行mock响应
* * `mock` 仅mock返回本地数据,不抓取保存响应
*/
mode: "auto" | "save" | "mock"
/**
* 抓取的数据要保存在哪个目录下,仅支持绝对路径,且目前必须存在
*/
directory: string
/**
* 哪些响应类型(Content-Type)数据会被保存
* * `string[]` 响应`Content-Type` 包含的类型会被保存, 比如 ["json", "js", "css"]
* * `string` 如果值是字符串,表示进行正则匹配,满足该正则表达式的 Content-Type 会被保存, 比如 "(json|js)"
*/
types: string[] | string
/**
* 抓取保存数据存在到本地目录时,文件存放方式
* * `hash` 本地文件保存时,以 `hash` 名的方式进行保存,hash是由 HTTP Method, Full URL 计算得到
* * `path` 本地文件按照URL的层级以目录的形式存放
*/
storage: "hash" | "path"
/**
* 用来设置返回mock数据时,哪些响应头会被输出
* * `string[]` 会被输出的完整响应头名称,比如 ["content-type"]
* * `string` 如果值是字符串,表示进行正则匹配,符合条件的响应头会被输出
*/
responseHeaders: string[] | string
}types 和 responseHeaders 的匹配算法实现如下:
function isMatch(match: string | string[], text: string) {
if (Array.isArray(match)) {
return match.some(type => text.includes(type));
}
if (typeof match === "string") {
try {
return new RegExp(match, "i").test(text);
} catch (ex) {
console.error(`[whistle.savemock] 不是有效的正则表达式: ${match}`);
}
}
return false;
}
// 满足以下匹配的响应才会被保存
if( isMatch(config.types, responseContentType) ) { saveToLocal(); }
if( isMatch(config.responseHeaders, responseHeaderName) ) { writeHeader(responseHeaderName, responseHeaderValue); }本地调试
先在 whistle.savemock 项目执行以下命令:
npm run ts:watch
npm run lack:watch