2.0.8 • Published 21 days ago

@flatjs/mock v2.0.8

Weekly downloads
-
License
MIT
Repository
-
Last release
21 days ago

@flatjs/mock

@flatjs/mock 使用指南

迅速启动本地 Mock 服务、方便快捷的模拟各种接口请求场景、模拟各种数据类型响应;

备注 1: 建议保持 Mock 数据的拟真性, 如图片尺寸、文字长短、姓名、日期、证件号码等等, 能提升理解度、美观度、也能发现 UI 的兼容性问题。 备注 2: Postman Collection: https://www.getpostman.com/collections/ae53e4a38a9de2e44b6a

Step1: 准备工作

  1. 安装 VsCode https://code.visualstudio.com;
  2. 打开 VsCode, 左侧菜单选择「 Extensions 」, 查找并安装 VsCode 插件: ESLint, Prettier - Code formatter;
  3. 学习 mock 数据的生成规则, 需要 VPN : https://github.com/nuysoft/Mock/wiki/Getting-Started;

Step2: 配置本地 hosts 文件, 目录: /etc/hosts

  1. 127.0.0.1 localhost dev.flatjs.com

Step3: 安装依赖 & 启动服务

  1. npm install -g @flatjs/cli yarn
  2. yarn
  3. flat mock

静态文件资源

地址
http://dev.flatjs.com:40000/static/example.png
http://dev.flatjs.com:40000/static/banner.png
http://dev.flatjs.com:40000/static/icon.png

Rest & Rest-nest

接口名接口地址
获取产品列表http://dev.flatjs.com:40000/api/rest/queryProductList?page=1&pageSize=10
获取用户信息http://dev.flatjs.com:40000/api/rest/queryUserinfo
获取订单列表http://dev.flatjs.com:40000/api/rest/queryOrderList?page=1&pageSize=10
获取订单详情http://dev.flatjs.com:40000/api/rest/queryOrderDetail?orderNo=1
支付订单http://dev.flatjs.com:40000/api/rest/payOrder?orderNo=1
图片上传http://dev.flatjs.com:40000/static/upload-files.png
获取图片流http://dev.flatjs.com:40000/api/rest/showImage?fileKey=idcardEmblem
模拟各种状态码, 500http://dev.flatjs.com:40000/api/rest/fake-500
登录 (nest)http://dev.flatjs.com:40000/api/rest/login/loginByUsername?username=abc&password=123456

Func-simple & Func-simple-nest

接口名接口地址
获取产品类目http://dev.flatjs.com:40000/static/func-simple.png
获取产品类目 (nest)http://dev.flatjs.com:40000/static/func-simple-nest.png
// 请求体 Request
{
  "protocol": {
    "functionCode": "queryProductList",
    "fromPlatform": "tc_app",
    "userId": "785d680efb8515c71715a694fa0afe81"
  },
  "param": {
    "page": 1,
    "pageSize": 10
  }
}
// 响应体 Response
{
  "code": "0000",
  "message": "success",
  "data": {}
}

Others(任意未预先匹配的路径)

接口名接口地址
unknownhttp://dev.flatjs.com:40000/api/a/b/c

Proxy (代理)

接口名接口地址
proxyhttp://dev.flatjs.com:40000/proxy/rest/queryUserinfo

gql

接口名接口地址
gqlhttp://dev.flatjs.com:40000/static/gql.png

The usages

npm i @flatjs/mock
// Install the following devDependencies.
"@types/express": "^4.17.7",
"@types/express-mung": "^0.5.2",
"@types/http-proxy-middleware": "^0.19.3",
"@types/mockjs": "^1.0.3",

The configuration of the flatjs.mock.js as below example

baseCwd: join(process.cwd(), `packages/mock/mocks`),
apiContext: '/api',
hostname: 'dev.flatjs.com',
port: 4000,
staticMap: {
  '/static': 'static',
},
mockMap: {
  '/func': { type: 'FUNC', defs: ['func'], middlewares: {res: otherFuncMiddleware.forFuncApiSimpleResponse()] } },
  '/rest': { type: 'REST', defs: ['rest']},
},
// Tor expressjs middleware cycle
// The outer middlewares defined by user should be executed in the final phase

// e.g. Below middleware will used to simplify response for `func`
otherRestMiddleware.forFuncApiSimpleResponse();

Features

  • Both support .ts ,.js mock services.
  • Provider class MockBase as base class for all mock services
  • Built in support mockjs
  • Proiders usually module exports.

Examples

  • The first scenario, auto instance class need @Mockable() for class
@mockable()
export default class MockProductService extends MockBase {
  @mockAlias("products")
  geProducts(_req: MockRequest, res: MockResponse): void {
    res.json({
      code: "0000",
      message: "func product",
      data: ["https://www.flatjs.com/blog/img/flatjs_avatar.png"],
    });
  }
}
  • The second scenario, auto instance class need @Mockable() for class
@mockable()
export class MockCatalogService extends MockBase {
  @mockAlias("catalog/list")
  getCatalogs(_req: MockRequest, res: MockResponse): void {
    res.json({
      code: "0000",
      message: "func catalogs",
      data: ["https://www.flatjs.com/blog/img/flatjs_avatar.png"],
    });
  }
}
  • The third scenario, use module.exports = new () the class decortor @Mockable is optional
class MockUserService extends MockBase {
  @mockAlias("product/list")
  getUsers(_req: MockRequest, res: MockResponse): void {
    res.json({
      data: ["https://www.flatjs.com/blog/img/flatjs_avatar.png"],
    });
  }
}
module.exports = new MockUserService();
  • The forth scenario
export function getAds(_req: MockRequest, res: MockResponse): void {
  res.json({
    code: "0000",
    message: "func ads",
    data: ["https://www.flatjs.com/blog/img/flatjs_avatar.png"],
  });
}

Use Http Proxy proxyMap

 ....
  proxyMap: {
    '/proxy': {
      target: 'https://fex.qa.tcshuke.com',
      pathRewrite: { '^/proxy': '' },
      router(req) {
        switch (req.query.env) {
          case 'me':
            return 'https://dev.flatjs.com:4000';
          case 'uat':
            return `https://fex.qa.tcshuke.com`;
        }
        return 'https://fex.qa.tcshuke.com';
      },
    },
  },
  // request `/proxy/mock/api/status/200?env=uat` ---> `https://fex.qa.tcshuke.com/mock/api/status/200?env=uat`

Use multer for file upload

import { mockAlias, MockBase, MockRequest, MockResponse } from "@flatjs/mock";
import fs from "fs";
import mimeTypes from "mime-types";
import multer from "multer";
import { join } from "path";

const storage = multer.diskStorage({
  destination: function (_req, _file, cb) {
    fs.mkdirSync(join(__dirname, "../static/uploads"), { recursive: true });
    cb(null, join(__dirname, "../static/uploads"));
  },
  filename: function (_req, file, cb) {
    const { mimetype, fieldname } = file || {};
    const extension = mimeTypes.extension(mimetype) as string;
    cb(null, `${fieldname}-${Date.now()}.${extension}`);
  },
});

class MockService extends MockBase {
  @mockAlias("/uploadFile")
  uploadFile(req: MockRequest, res: MockResponse): void {
    const upload = multer({
      storage,
    }).any();

    upload(req, res, () => {
      const files = (req.files as Express.Multer.File[]) || [];
      res.json({
        code: "0000",
        message: "upload files",
        data: {
          ...req.body,
          fieldnames: files.map(
            (s) => `${this.$hostUri(req)}/static/uploads/${s.filename}`
          ),
        },
      });
    });
  }
}

module.exports = new MockService();

Notes

Note, it we want to using import or require with cache First we can't include this folder into mockMap of flatjs.mock.js Second we can't use importFresh() @example

mockMap: {
  '/func': { type: 'FUNC', defs: ['func'], middlewares: {} },
  '/rest': { type: 'REST', defs: ['rest'], middlewares: {} },
},
the `defs` config should not include any `folders` that we want to cache.
2.1.0-next.4

21 days ago

2.1.0-next.2

25 days ago

2.1.0-next.1

25 days ago

2.1.0-next.3

25 days ago

2.1.0-next.0

1 month ago

2.0.7

1 month ago

2.0.8

1 month ago

2.0.6

2 months ago

2.0.5

2 months ago

2.0.4

2 months ago

2.0.3

3 months ago

2.0.2

5 months ago

2.0.1

5 months ago

2.0.0

6 months ago

1.8.1-next.56

10 months ago

1.8.1-next.55

10 months ago

1.8.1-next.58

10 months ago

1.8.1-next.57

10 months ago

1.8.1-next.59

10 months ago

1.8.1-next.61

10 months ago

1.8.1-next.60

10 months ago

1.8.1-next.63

10 months ago

1.8.1-next.62

10 months ago

1.8.1-next.65

10 months ago

1.8.1-next.64

10 months ago

1.8.1-next.67

10 months ago

1.8.1-next.66

10 months ago

1.8.1-next.69

9 months ago

1.8.1-next.68

9 months ago

2.0.0-next.2

7 months ago

2.0.0-next.3

7 months ago

2.0.0-next.1

7 months ago

1.8.1-next.70

9 months ago

1.8.1-next.72

9 months ago

1.8.1-next.71

9 months ago

1.8.1-next.74

9 months ago

1.8.1-next.73

9 months ago

1.8.1-next.76

9 months ago

1.8.1-next.75

9 months ago

1.8.1-next.78

9 months ago

1.8.1-next.77

9 months ago

1.8.1-next.79

9 months ago

1.8.1-next.81

8 months ago

1.8.1-next.80

8 months ago

1.8.1-next.83

7 months ago

1.8.1-next.82

8 months ago

1.8.1-next.85

7 months ago

1.8.1-next.84

7 months ago

1.8.1-next.49

11 months ago

1.8.1-next.48

11 months ago

1.8.1-next.50

11 months ago

1.8.1-next.52

11 months ago

1.8.1-next.51

11 months ago

1.8.1-next.54

10 months ago

1.8.1-next.53

10 months ago

1.8.1-next.47

11 months ago

1.8.1-next.20

12 months ago

1.8.1-next.23

12 months ago

1.8.1-next.25

12 months ago

1.8.1-next.24

12 months ago

1.8.1-next.27

12 months ago

1.8.1-next.26

12 months ago

1.8.1-next.29

12 months ago

1.8.1-next.28

12 months ago

1.8.1-next.30

12 months ago

1.8.1-next.32

11 months ago

1.8.1-next.31

11 months ago

1.8.1-next.34

11 months ago

1.8.1-next.33

11 months ago

1.8.1-next.36

11 months ago

1.8.1-next.35

11 months ago

1.8.1-next.38

11 months ago

1.8.1-next.37

11 months ago

1.8.1-next.39

11 months ago

1.8.1-next.41

11 months ago

1.8.1-next.40

11 months ago

1.8.1-next.43

11 months ago

1.8.1-next.42

11 months ago

1.8.1-next.45

11 months ago

1.8.1-next.44

11 months ago

1.8.1-next.46

11 months ago

1.7.3

11 months ago

1.7.2

12 months ago

1.5.26-alpha.1

1 year ago

1.5.26-alpha.0

1 year ago

1.8.1-next.18

12 months ago

1.8.1-next.17

12 months ago

1.8.1-next.19

12 months ago

1.5.23

1 year ago

1.5.25

1 year ago

1.5.24

1 year ago

1.5.27

1 year ago

1.5.29

1 year ago

1.5.28

1 year ago

1.5.16

1 year ago

1.5.15

1 year ago

1.5.19

1 year ago

1.5.12

1 year ago

1.5.14

1 year ago

1.5.13

1 year ago

1.5.9

1 year ago

1.5.8

1 year ago

1.5.7

1 year ago

1.5.6

1 year ago

1.5.4

2 years ago

1.5.11

1 year ago

1.4.21

2 years ago

1.5.0

2 years ago

1.4.20

2 years ago

1.4.15

2 years ago

1.4.16

2 years ago

1.4.14

2 years ago

1.4.13

2 years ago

1.4.12

2 years ago

1.4.11

2 years ago

1.4.10

2 years ago

1.4.9

2 years ago

1.4.8

2 years ago

1.4.5

2 years ago

1.4.4

2 years ago

1.4.3

2 years ago

1.4.7

2 years ago

1.4.2

2 years ago

1.4.1

2 years ago

1.2.96

2 years ago

1.2.97

2 years ago

1.3.7

2 years ago

1.3.5

2 years ago

1.3.4

2 years ago

1.3.2

2 years ago

1.3.1

2 years ago

1.2.92

2 years ago

1.2.94

2 years ago

1.2.95

2 years ago

1.2.81

2 years ago

1.2.82

2 years ago

1.2.85

2 years ago

1.2.86

2 years ago

1.2.83

2 years ago

1.2.88

2 years ago

1.2.90

2 years ago

1.2.91

2 years ago

1.2.78

2 years ago

1.2.77

2 years ago

1.2.75

3 years ago

1.2.76

3 years ago

1.2.72

3 years ago

1.2.71

3 years ago

1.2.67

3 years ago

1.2.64

3 years ago

1.2.65

3 years ago

1.2.60

3 years ago

1.2.57

3 years ago

1.2.56

3 years ago

1.2.55

3 years ago

1.2.53

3 years ago

1.2.52

3 years ago

1.2.50

3 years ago

1.2.51

3 years ago

1.2.49

3 years ago

1.2.48

3 years ago

1.2.42

3 years ago

1.2.40

3 years ago

1.2.39

3 years ago

1.2.31

3 years ago

1.2.35

3 years ago

1.2.32

3 years ago

1.2.33

3 years ago

1.2.38

3 years ago

1.2.30

3 years ago

1.2.28

3 years ago

1.2.27

3 years ago

1.2.24

3 years ago

1.2.23

3 years ago

1.2.21

3 years ago

1.2.18

3 years ago

1.2.17

3 years ago

1.2.16

3 years ago