Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端mock方案 #31

Open
jiangshanmeta opened this issue Sep 3, 2020 · 0 comments
Open

前端mock方案 #31

jiangshanmeta opened this issue Sep 3, 2020 · 0 comments

Comments

@jiangshanmeta
Copy link
Owner

jiangshanmeta commented Sep 3, 2020

为了在开发、维护阶段减少对后端的依赖,也为了减少联调阶段的风险,前端需要mock环境来模拟接口返回的数据。下面介绍一种基于koa和better-mock实现的mock方案。

better-mock类似于Mock.js,由于后者现在已经停止维护,所以作者基于TypeScript重写了。虽然这两个库都是支持重载XMLHttpRequest来拦截ajax请求,但是这个方式并不好,一个原因是需要区分开发和生产环境 决定是否要加载mock数据,这样代码会有点脏,另一个原因,也是更重要的原因,是我们无法通过network进行调试,我们其实希望mock服务能在开发体验上接近于后端提供的接口服务,于是采用koa搭建了一个简易的后端服务。

先看一下依赖:

"dependencies": {
    "better-mock": "^0.2.6",
    "koa": "^2.13.0",
    "koa-router": "^9.4.0",
    "nodemon": "^2.0.4"
}

nodemon是用来检测文件变更然后重启node服务的。

在实际业务中,后端返回的json格式是这样:

{
    code:"0000",
    success:true,
    msg: "操作成功",
    data:"",
}

其中data是前端真正需要的数据,类型不定。

对于每一个接口,可以配置成如下格式:

{
    path: '/mock',
    method: 'post',
    mock: {
        'data|0-5': [
            {
                name: '@cword(5,15)',
                companyType: '@integer(1,5)',
            },
        ],
    },
},

path是请求的路径,method是请求的方法,mock里面的内容是我们要mock的主题,之所以需要加一层mock,是因为data可能为数组(此时better-mock需要 data|min-max 这种格式),也可能为其他格式,为了方便外面处理所以包一层。

基于koa-router控制路由并生成返回mock数据:

const responseBody = {
    code: '0000',
    success: true,
    msg: '操作成功',
};

config.forEach((item) => {
    router[item.method](item.path, (ctx) => {
        ctx.body = {
            ...responseBody,
            data: Mock.mock(item.mock).data,
        };
    });
});

完整代码参见附件

mock.zip

typescript版本

mock.zip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant