@tzxhy/vite-generate-mock
TypeScript icon, indicating that this package has built-in type declarations

0.0.1 • Public • Published

@tzxhy/vite-generate-mock

根据 swagger.json 文档,创建 vite-plugin-mock 所用的 ts 文件。

安装

yarn add @tzxhy/vite-generate-mock -D

使用

创建自定义文件,如:

// scripts/generate-mock.js

// 用于生成mock结构
/* eslint-disable */
const path = require('path');
const fs = require('fs');
const generate = require('@tzxhy/vite-generate-mock').default;
let customJsonConf = {};
try {
    customJsonConf = require('../mock/custom-mock-conf');
} catch(e) {
    console.log('如果需要自定义代理,创建 mock/custom-mock-conf.js 文件内容如:' + `
module.exports = {
    '/v1/mec/device/create_sensor': {
        url: '/api/mec/device/create_sensor_new',
        method: 'post',
        response: () => ({
            errCode: 0,
            errMsg: 'success',
            errDetail: Random.string(),
            data: {
                rsuSerial: Random.string(),
            },
        }),
    },
};`);
}

const customInterfaceKeys = Object.keys(customJsonConf);

const mockCodes = generate({
    fileHeader: '',
    // 指定 swagger.json 文件地址
    apiPath: path.join(__dirname, '..', 'swagger', 'api.swagger.json'),
    apiPathRewrite(apiPath) {
        return apiPath.replace('/v1', '/api');
    },
    // api 替换,使用自定义的内容
    apiReplace(apiPath) {
        if (customInterfaceKeys.includes(apiPath)) {
            return this.returnObj(customJsonConf[apiPath]);
        }
    },
    // this 绑定了辅助函数;apiPath为接口地址;curveKeyName为key名称;curveLevel为嵌套级别。从1开始。
    // apiPath 为转换前的path
    responseAdapter(apiPath, curveKeyName, curveLevel) {
        if (curveKeyName === 'totalPages') {
            return this.createNumberLiteral(100);
        }
        if (curveKeyName === 'count') {
            return this.createNumberLiteral(10000);
        }
        if (curveKeyName === 'id') {
            return this.createRandomNumber(1, 1000);
        }
        if (curveKeyName === 'alertingNum'
        || curveKeyName === 'totalAlerting'
        || curveKeyName === 'totalErrors'
        || curveKeyName === 'totalHistoryErrors'
        || curveKeyName === 'totalHistoryAlerting'
        
        ) {
            return this.createRandomNumber(1, 200);
        }
        if (curveKeyName === 'keepingTime') {
            return this.createRandomNumber(1000 * Math.floor(Math.random() * 1e3), 1e8);
        }
        if (curveKeyName === 'timestamp') {
            return this.createStringLiteral(new Date().valueOf() + '')
        }
        if (curveKeyName === 'errCode') {
            return this.createNumberLiteral(0);
        }
        if (curveKeyName === 'errMsg') {
            return this.createStringLiteral('success');
        }
    }
});

// 产物地址
const mockDest = path.join(__dirname, '..', 'mock', 'api.ts');
fs.writeFileSync(mockDest, mockCodes);
console.log('mock源文件已生成至: ' + mockDest);

配置 package.json

{
    "scripts": {
        "start-with-mock": "yarn typings && yarn generate-mock && vite --open --mode mock",
        "generate-mock": "node scripts/generate-mock",
        "typings": "other things"
    }
}

配置 vite.config.js,如下:

import {
    defineConfig,
} from 'vite';

import {
    viteMockServe,
} from 'vite-plugin-mock';

export default defineConfig((env) => {
    const plugins = [];
    if (env.mode === 'mock') {
        console.log('use mock server...');
        // mock plugin
        plugins.push(
            viteMockServe({
                mockPath: 'mock',
                localEnabled: true,
            }),
        );
        // scripts/generate-mock.js 文件地址
        const mockGenerate = path.join(__dirname, 'scripts', 'generate-mock.js');

        // 文件更新,那么重新生成mock数据
        fs.watch(mockGenerate, () => {
            childProcess.exec('node ' + mockGenerate, (err, std) => {
                console.log(std);
            });
        });

        // 自定义文件更新,同样触发更新
        try {
            const customMock = path.join(__dirname, 'mock', 'custom-mock-conf.js');
            fs.watch(customMock, () => {
                childProcess.exec('node ' + mockGenerate, (err, std) => {
                    console.log(std);
                });
            });
        } catch (error) {
            console.log('watch custom mock error', '\n', error);
        }
    return {
        plugins,
        // ... other configs
    }
})

然后开启 mock 开发 即可: yarn start-with-mock

Package Sidebar

Install

npm i @tzxhy/vite-generate-mock

Weekly Downloads

1

Version

0.0.1

License

none

Unpacked Size

21.1 kB

Total Files

4

Last publish

Collaborators

  • tzxhy