vbenjs / vite-plugin-mock

A mock plugin for vite.use mockjs.
MIT License
625 stars 96 forks source link

建议Mock file文件[test.ts]默认导出是个方法,以便可以传递配置参数 #61

Open lancemach opened 2 years ago

lancemach commented 2 years ago

setupProdMockServer方法可以自定义配置,但是localServer不能自定义配置, 我主要是应用Mockjs的timeout可以配置区间值’200-800‘ms,开发者也可以根据自己时间需求传递配置参数 例如:


import { MockMethod } from 'vite-plugin-mock'
export default (loadEnv: envConfig) => {
  return [
    {
      url: '/api/get',
      method: 'get',
      response: ({ query }) => {
        return {
          code: 0,
          data: {
            name: 'vben',
          },
        }
      },
    },
    {
      url: '/api/post',
      method: 'post',
      timeout: 2000,
      response: {
        code: 0,
        data: {
          name: 'vben',
        },
      },
    },
    {
      url: '/api/text',
      method: 'post',
      rawResponse: async (req, res) => {
        let reqbody = ''
        await new Promise((resolve) => {
          req.on('data', (chunk) => {
            reqbody += chunk
          })
          req.on('end', () => resolve(undefined))
        })
        res.setHeader('Content-Type', 'text/plain')
        res.statusCode = 200
        res.end(`hello, ${reqbody}`)
      },
    },
  ] as MockMethod[]
}