前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >simple-mock-api

simple-mock-api

作者头像
felix
发布2018-07-02 17:29:33
6710
发布2018-07-02 17:29:33
举报
文章被收录于专栏:Felix的技术分享Felix的技术分享

项目中有一个Activiy需要轮询多个接口,实时刷新数据。这里很多业务逻辑都需要依赖当前的状态,所以简单写了一个服务端,用于生成一些mock data,并且支持数据实时刷新。

项目地址:simple-mock-api

挂到腾讯云上就可以公网访问了。


simple-mock-api

Use json-server make this simple mock api server.

Usage

  1. checkout this project,and cd
  2. type npm install in terminal to install dependences
  3. run node app.js
  4. get result via your configed cgi,like http://localhost:3000/get_match_players

Config

You can config

代码语言:javascript
复制
cgi,
default json file,
custom handle the request, modify json response

Example

Create a get_match_detail.json file in data folder.

代码语言:javascript
复制
{
  "state": 1,
  "title":"NBA",
  "time":"2017-01-01",
  "homescore": "101",
  "guestscore": "115"
}

In config.js config you mock api

代码语言:javascript
复制
var config = [
{
    "cgi":"/get_match_detail",
    "filepath":"data/get_match_detail.json",
    "need_cache":true,
    "hookfunc":func_get_match_detail
},
{
    "cgi":"/get_match_players",
    "filepath":"data/get_match_players.json",
    "need_cache":false,
    "hookfunc":func_get_match_players
},

];

You can custom handle the request by define your custom “hookfunc”, like this:

代码语言:javascript
复制
var func_get_match_detail = function(defaultObj,req) {
    //increase homescore every time
    var homescore = parseInt(defaultObj.homescore)+1+"";
    defaultObj.homescore = homescore;
}

The param defaultObj means the parsed json object you defined in the key “filepath”.

If the key “need_cache” seted true, than your hookfunc can change the defaultObj in the cache forever.

Start JSON Server

代码语言:javascript
复制
$ node app.js

Now if you go to http://localhost:3000/get_match_detail, you’ll get

代码语言:javascript
复制
{
  "state": 1,
  "title":"NBA",
  "time":"2017-01-01",
  "homescore": "102",
  "guestscore": "115"
}

and the homescore’s value changed every time when you go to the same link.

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年01月01日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • simple-mock-api
    • Usage
      • Config
        • Example
          • Start JSON Server
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档