Associated tags: #vue #vite #mock # yAPI # easyMock # front-end

background

At the beginning of the project, the backend students only provided interface documents, while the front-end students needed to mock data according to the documents in order to make the functional process run smoothly.

Technology research

How to elegantly mock data, whether through cloud platform YAPI, easy-Mock, or native mock schemes. Currently using a personally-built Easy-mock service.

EasyMock

  • Easy Mock/Easy Mock at Master (github.com)
  • Advantages:
    • Support Intranet deployment
    • Interface proxy support
    • Support Swagger && OpenAPI import
    • Support for mock.js syntax
    • Supports restC interface preview
    • Supports custom response configuration
    • Support team management
  • Disadvantages:
    • Unsupported documents
    • The cloud deployment

YApi

  • Liverpoolfc.tv: github.com/ymfe/yapi
  • Advantages:
    • Support Intranet deployment
    • Support for automated testing
    • Supports interface debugging such as Postman
    • Flat rights management
    • Support for mock.js syntax
    • Support custom plug-ins
    • Supports parameter and response format preview
  • Disadvantages:
    • Cloud deployment is required

Local mock

  • Official website: Mock.js (mockjs.com)
  • Advantages:
    • Follow the project code
    • Support JS syntax, can be customized request and response
    • Follow Git with version control
  • disadvantages
    • People outside the project cannot view it

The project practice

At present, I am using Easy-Mock to build cloud service, but the tedious thing is that it has not been deployed to the company and the swagger document at the back end cannot be synchronized. Finally, I decided to adopt the local mock scheme and put the mock code into the project Git repository. When everyone develops their own functions, Create your own mock files.

Install dependencies

At present, the team project uses vUE framework 2.x version, Vite 2.x version construction, PNPM for package management.

You need to install the following dependencies on the command line

PNPM I mockjs viet-plugin-mock -d is a plugin for viteCopy the code

Project configuration

Update vite. Config. Js

import { createVuePlugin } from 'vite-plugin-vue2';
import { viteMockServe } from 'vite-plugin-mock';

// https://vitejs.dev/config/
export default ({ command }) => {
  console.log('current command is ', command);
  return {
    resolve: {
      alias: [{ find: The '@'.replacement: '/src'}],},css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@import "@/assets/style/index.scss"; `,}}},plugins: [
      createVuePlugin(),
      viteMockServe({
        ignore: / ^ \ _ /.// Tools files starting with _ are ignored
        mockPath: 'mock'.// In the mock directory
        prodEnabled: false.// Turn off the production environment mock})]}; };Copy the code

The mock folder is created in the project root directory along with the mock/_utils.ts utility method file

// Successful response
export function success<T = Recordable> (data: T, msg = 'success') {
  return {
    code: 0,
    data,
    msg,
  };
}

// The list responded successfully
export function listSuccess<T = any> (
  page: number,
  limit: number,
  list: T[],
  { msg = 'success' } = {}
) {
  const pageData = pagination(page, limit, list);

  return {
    ...success({
      list: pageData,
      total: list.length,
    }),
    msg,
  };
}

// Error response. The first two bits of the error code are service classification errors, and the last four bits are internal service errors
// An error code starting with 1 is a gateway error or a universal authentication error. The service side cannot declare an error code starting with 1
export function fail(msg = 'mock mistakes', code = 100000, data = null) {
  return {
    code,
    data,
    msg,
  };
}

// Paging method
export function pagination<T = any> (page: number, limit: number, list: T[]) :T[] {
  const offset = (page - 1) * Number(limit);
  const ret =
    offset + Number(limit) >= list.length
      ? list.slice(offset, list.length)
      : list.slice(offset, offset + Number(limit));
  return ret;
}

// Request parameter type
export interface requestParams {
  method: string; body: any; headers? : { authorization? : string }; query: any; }// Get the request header authentication token
export function getRequestToken({ headers, }: requestParams) :string | undefined {
  returnheaders? .authorization; }Copy the code

Create mock/demo.ts file to mock out an interface for adding, deleting, modifying, and checking

import { MockMethod } from 'vite-plugin-mock';
import Mock from 'mockjs';
import { success, fail, listSuccess, requestParams } from '.. /_utils.ts';

// Mock a custom mobile phone number
Mock.Random.extend({
  phone() {
    return Mock.mock(/1[3456789]\d{9}/); }});export default [
  / / create
  {
    url: '/demos/create'.timeout: 1000.method: 'post'.response({ body }) {
      return success({
        id: 123.createdAt: '@now'.updatedAt: '@now'. body, }); }},/ / delete
  {
    url: '/demos/delete'.timeout: 1000.method: 'delete'.response({ query }) {
      if (parseInt(query.id) === 1) {
        return fail('Content does not exist');
      }
      return success(null.'Deleted successfully'); }},/ / modify
  {
    url: '/demos/update'.timeout: 1000.method: 'put'.response({ query, body }) {
      returnsuccess({ ... body,id: query.id,
        updatedAt: '@now'}); }},// Query the list
  {
    url: '/demos/list'.timeout: 1000.method: 'get'.response({ query }: requestParams) {
      const res: any = [];
      for (let i = 0; i < 88; i++) {
        res.push({
          id: i + 1.'type|1': ['Administrator'.'Whitelist'].'userId|100000-200000': 100.username: '@cname()'.createdAt: '@datetime'.updatedAt: '@now'}); }returnlistSuccess(query.page, query.limit, res); }},// For details
  {
    url: '/demos/detail'.timeout: 1000.method: 'get'.response({ query }) {
      return success({
        id: parseInt(query.id),
        name: '@cname'.email: '@email'.bio: '@cparagraph'.phone: Mock.Random.phone(),
        createdAt: '@datetime'.updatedAt: '@now'}); }},]as MockMethod[];
Copy the code

Results demonstrate

conclusion

At present, the front-end project and back-end project of the team are relatively independent and there is no series, so the local Mock method can solve the problem of front-end interface dependence with low cost, high customization and high efficiency.

If your company has a good infrastructure, it may be a priority to deploy a more customizable YApi for interface management, linking documents and other tool flows, rather than a large team project. Start from the back end to create Swagger → YApi → front-end Mock → test interface automation → product look up interface documents. When the whole link is cleared up and a standardized development process is created, the research and development efficiency will be greatly improved and the communication cost caused by interface will be reduced.

Reference documentation

  1. Mock.js (mockjs.com)
  2. Github.com/anncwb/vite…
  3. Github.com/anncwb/vue-…