lazy-mock ,一个生成后端模拟数据的懒人工具
阅读本文大概需要 3 分钟。
来自:https://juejin.im/post/6871592049485807630
前言
最近发现一个比较好玩的东东,一个不需要 mock 并且匹配正则的接口直接转发到后端地址的小工具。
install
yarn create @lowcoding/mock
start
yarn start
lowcode-mock 默认支持跨域,前端项目中可不必再配置代理,直接请求 lowcode-mock 起的服务即可。
mock
import KoaRouter from 'koa-router'
import proxy from '../middleware/Proxy'
import { delay } from '../lib/util'
let Mock = require('mockjs')
let Random = Mock.Random
const router = new KoaRouter()
router.get('/your-mock-api', (ctx) => {
ctx.body = '你的第一个mock接口'
})
module.exports = router
根据 YAPI 生成 mock
根据 JSON 生成 mock
通过 JSON 数据生成的 mock 接口需要手动修改路由地址。
根据字段类型或字段名称生成特定的 mock 数据
"yapi-code.mockKeyWordLike": {
"icon": "Random.image('48x48')",
"img":"Random.image('48x48')",
"image":"Random.image('48x48')",
"code": "200&&number",
"name":"'模糊匹配后生成的mock'"
},
"yapi-code.mockKeyWordEqual": {
"message": "'这是一条精确的mock'",
"total": 200,
},
"yapi-code.mockString": "Random.cword(5, 6)",
"yapi-code.mockBoolean": "Random.boolean()",
"yapi-code.mockNumber": "Random.natural(100,1000)"
const json = {
code: 100,
message: '请求成功',
result: {
list: [
{
code: '注意这是一个字符串的code',
name: '张三',
icon: '',
actived: false,
},
],
total: 0,
},
}
.get(`xxxxx`, async (ctx, next) => {
const list1 = []
for (let i = 0; i < 3; i++) {
list1.push({
code: Random.cword(5, 6),
name: '模糊匹配后生成的mock',
icon: Random.image('48x48'),
actived: Random.boolean(),
})
}
ctx.body = {
code: 200,
message: '这是一条精确的mock',
result: { list: list1, total: 200 },
}
})
{
"code": 200,
"message": "这是一条精确的mock",
"result": {
"list": [
{
"code": "八别因教者活",
"name": "模糊匹配后生成的mock",
"icon": "http://dummyimage.com/48x48",
"actived": true
},
{
"code": "毛着何工时白",
"name": "模糊匹配后生成的mock",
"icon": "http://dummyimage.com/48x48",
"actived": false
},
{
"code": "县称县单下外",
"name": "模糊匹配后生成的mock",
"icon": "http://dummyimage.com/48x48",
"actived": true
}
],
"total": 200
}
}
延时
import KoaRouter from 'koa-router'
import proxy from '../middleware/Proxy'
import { delay } from '../lib/util'
let Mock = require('mockjs')
let Random = Mock.Random
const router = new KoaRouter()
router.get('/delay', (ctx) => {
delay(3) // 3 秒后返回结果
ctx.body = 'delay'
})
可用于测 loading 效果。
http 异常状态码
router.get('/httpError', (ctx) => {
ctx.status = 401
ctx.body = 'http 401'
})
代理
router.get('/proxy', proxy('https://github.com/wjkang/lowcode-mock'), (ctx) => { ctx.body = 'https://github.com/wjkang/lowcode-mock'})
来自 /proxy 的请求转发到 https://github.com/wjkang/lowcode-mock/proxy ,用于后端接口可联调的时候跳过本地 mock,转发请求到后端接口。
router.all(new RegExp('^/lowcode/mock/(|^$)'), proxy('https://github.com/wjkang/lowcode-mock'))
不需要 mock 并且匹配正则的接口直接转发到后端地址。
源码地址
推荐阅读:
微信扫描二维码,关注我的公众号
朕已阅
评论