2.4.0 • Published 8 months ago

@flatjs/mock v2.4.0

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months 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.4.0

9 months ago

2.4.1-next.0

9 months ago

2.4.1-next.1

9 months ago

2.4.1-next.2

8 months ago

2.4.1-next.3

8 months ago

2.4.1-next.4

8 months ago

2.3.0

11 months ago

2.3.2

11 months ago

2.3.1

11 months ago

2.3.4

11 months ago

2.3.3

11 months ago

2.3.6

10 months ago

2.3.5

11 months ago

2.2.1

1 year ago

2.2.2

1 year ago

2.3.7

10 months ago

2.3.6-next.0

11 months ago

2.3.0-next.1

12 months ago

2.3.0-next.0

1 year ago

2.2.0

1 year ago

2.1.3

1 year ago

2.1.2

1 year ago

2.1.0-next.13

2 years ago

2.1.0-next.12

2 years ago

2.1.0-next.11

2 years ago

2.1.0-next.10

2 years ago

2.1.0-next.14

2 years ago

2.1.0-next.9

2 years ago

2.1.0-next.6

2 years ago

2.1.0-next.8

2 years ago

2.1.0-next.7

2 years ago

2.1.1

2 years ago

2.1.0

2 years ago

2.1.0-next.5

2 years ago

2.1.0-next.4

2 years ago

2.1.0-next.2

2 years ago

2.1.0-next.1

2 years ago

2.1.0-next.3

2 years ago

2.1.0-next.0

2 years ago

2.0.7

2 years ago

2.0.8

2 years ago

2.0.6

2 years ago

2.0.5

2 years ago

2.0.4

2 years ago

2.0.3

2 years ago

2.0.2

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

1.8.1-next.56

3 years ago

1.8.1-next.55

3 years ago

1.8.1-next.58

3 years ago

1.8.1-next.57

3 years ago

1.8.1-next.59

3 years ago

1.8.1-next.61

3 years ago

1.8.1-next.60

3 years ago

1.8.1-next.63

3 years ago

1.8.1-next.62

3 years ago

1.8.1-next.65

3 years ago

1.8.1-next.64

3 years ago

1.8.1-next.67

3 years ago

1.8.1-next.66

3 years ago

1.8.1-next.69

3 years ago

1.8.1-next.68

3 years ago

2.0.0-next.2

2 years ago

2.0.0-next.3

2 years ago

2.0.0-next.1

2 years ago

1.8.1-next.70

3 years ago

1.8.1-next.72

2 years ago

1.8.1-next.71

2 years ago

1.8.1-next.74

2 years ago

1.8.1-next.73

2 years ago

1.8.1-next.76

2 years ago

1.8.1-next.75

2 years ago

1.8.1-next.78

2 years ago

1.8.1-next.77

2 years ago

1.8.1-next.79

2 years ago

1.8.1-next.81

2 years ago

1.8.1-next.80

2 years ago

1.8.1-next.83

2 years ago

1.8.1-next.82

2 years ago

1.8.1-next.85

2 years ago

1.8.1-next.84

2 years ago

1.8.1-next.49

3 years ago

1.8.1-next.48

3 years ago

1.8.1-next.50

3 years ago

1.8.1-next.52

3 years ago

1.8.1-next.51

3 years ago

1.8.1-next.54

3 years ago

1.8.1-next.53

3 years ago

1.8.1-next.47

3 years ago

1.8.1-next.20

3 years ago

1.8.1-next.23

3 years ago

1.8.1-next.25

3 years ago

1.8.1-next.24

3 years ago

1.8.1-next.27

3 years ago

1.8.1-next.26

3 years ago

1.8.1-next.29

3 years ago

1.8.1-next.28

3 years ago

1.8.1-next.30

3 years ago

1.8.1-next.32

3 years ago

1.8.1-next.31

3 years ago

1.8.1-next.34

3 years ago

1.8.1-next.33

3 years ago

1.8.1-next.36

3 years ago

1.8.1-next.35

3 years ago

1.8.1-next.38

3 years ago

1.8.1-next.37

3 years ago

1.8.1-next.39

3 years ago

1.8.1-next.41

3 years ago

1.8.1-next.40

3 years ago

1.8.1-next.43

3 years ago

1.8.1-next.42

3 years ago

1.8.1-next.45

3 years ago

1.8.1-next.44

3 years ago

1.8.1-next.46

3 years ago

1.7.3

3 years ago

1.7.2

3 years ago

1.5.26-alpha.1

3 years ago

1.5.26-alpha.0

3 years ago

1.8.1-next.18

3 years ago

1.8.1-next.17

3 years ago

1.8.1-next.19

3 years ago

1.5.23

3 years ago

1.5.25

3 years ago

1.5.24

3 years ago

1.5.27

3 years ago

1.5.29

3 years ago

1.5.28

3 years ago

1.5.16

3 years ago

1.5.15

3 years ago

1.5.19

3 years ago

1.5.12

3 years ago

1.5.14

3 years ago

1.5.13

3 years ago

1.5.9

3 years ago

1.5.8

3 years ago

1.5.7

3 years ago

1.5.6

3 years ago

1.5.4

3 years ago

1.5.11

3 years ago

1.4.21

3 years ago

1.5.0

3 years ago

1.4.20

3 years ago

1.4.15

3 years ago

1.4.16

3 years ago

1.4.14

4 years ago

1.4.13

4 years ago

1.4.12

4 years ago

1.4.11

4 years ago

1.4.10

4 years ago

1.4.9

4 years ago

1.4.8

4 years ago

1.4.5

4 years ago

1.4.4

4 years ago

1.4.3

4 years ago

1.4.7

4 years ago

1.4.2

4 years ago

1.4.1

4 years ago

1.2.96

4 years ago

1.2.97

4 years ago

1.3.7

4 years ago

1.3.5

4 years ago

1.3.4

4 years ago

1.3.2

4 years ago

1.3.1

4 years ago

1.2.92

4 years ago

1.2.94

4 years ago

1.2.95

4 years ago

1.2.81

4 years ago

1.2.82

4 years ago

1.2.85

4 years ago

1.2.86

4 years ago

1.2.83

4 years ago

1.2.88

4 years ago

1.2.90

4 years ago

1.2.91

4 years ago

1.2.78

4 years ago

1.2.77

4 years ago

1.2.75

4 years ago

1.2.76

4 years ago

1.2.72

4 years ago

1.2.71

4 years ago

1.2.67

4 years ago

1.2.64

4 years ago

1.2.65

4 years ago

1.2.60

4 years ago

1.2.57

4 years ago

1.2.56

4 years ago

1.2.55

4 years ago

1.2.53

5 years ago

1.2.52

5 years ago

1.2.50

5 years ago

1.2.51

5 years ago

1.2.49

5 years ago

1.2.48

5 years ago

1.2.42

5 years ago

1.2.40

5 years ago

1.2.39

5 years ago

1.2.31

5 years ago

1.2.35

5 years ago

1.2.32

5 years ago

1.2.33

5 years ago

1.2.38

5 years ago

1.2.30

5 years ago

1.2.28

5 years ago

1.2.27

5 years ago

1.2.24

5 years ago

1.2.23

5 years ago

1.2.21

5 years ago

1.2.18

5 years ago

1.2.17

5 years ago

1.2.16

5 years ago