diff --git a/.vscode/settings.json b/.vscode/settings.json index 131abfb..f166c87 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -11,5 +11,8 @@ "proxied", "referer" ], - "typescript.tsdk": "node_modules/typescript/lib" + "typescript.tsdk": "node_modules/typescript/lib", + "markdownlint.config": { + "no-inline-html": false + } } diff --git a/README.md b/README.md index 03f31f1..dddde03 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@


+

npm node-current @@ -67,6 +68,7 @@ pnpm add -D vite-plugin-mock-dev-server ### Configuration `vite.config.ts` + ``` ts import { defineConfig } from 'vite' import mockDevServerPlugin from 'vite-plugin-mock-dev-server' @@ -84,6 +86,7 @@ export default defineConfig({ } }) ``` + The plugin will read the configuration of `server.proxy` or `options.prefix`, and enable mock matching for matched URLs. The plugin will also read the `define` configuration, which supports direct use in mock files. @@ -97,6 +100,7 @@ The plugin will also read the `define` configuration, which supports direct use By default, write mock data in the `mock` directory of your project's root directory: `mock/**/*.mock.ts` : + ``` ts import { defineMock } from 'vite-plugin-mock-dev-server' @@ -113,6 +117,7 @@ export default defineMock({ Vite plugin `vite.config.ts` + ``` ts import { defineConfig } from 'vite' import mockDevServerPlugin from 'vite-plugin-mock-dev-server' @@ -192,6 +197,7 @@ export default defineConfig({ **Default:** `{}` example: Configure to file upload dir + ``` ts MockDevServerPlugin({ formidableOptions: { @@ -206,6 +212,12 @@ export default defineConfig({ **Default:** `{}` +- `options.bodyParserOptions` + + Configure to `co-body`, see [co-body](https://github.com/cojs/co-body#options) + + **Default:** `{}` + - `options.build` The configuration needed to build a small, independently deployable mock service. @@ -236,7 +248,7 @@ export default defineConfig({ - `options.priority` - Custom path matching rule priority。[read more](#Custom-Path-Matching-Priority) + Custom path matching rule priority。[read more](#custom-path-matching-priority) **Default:** `undefined` @@ -399,6 +411,7 @@ export default defineMock({ }, }) ``` + ``` ts // Configure the WebSocket mock export default defineMock({ @@ -486,8 +499,10 @@ type defineMockData = ( ) => [getter, setter] & { value: T } ``` -#### Exp: +### Exp + `data.ts` + ```ts import { defineMockData } from 'vite-plugin-mock-dev-server' @@ -496,7 +511,9 @@ export default defineMockData('posts', [ { id: '2', title: 'title2', content: 'content2' }, ]) ``` + `*.mock.ts` + ```ts import { defineMock } from 'vite-plugin-mock-dev-server' import posts from './data' @@ -529,6 +546,7 @@ export default defineMock([ The priority of the path matching rules built into the plugin can already meet most needs, but if you need more flexible customization of the matching rule priority, you can use the `priority` parameter. Exp: + ```ts import { defineConfig } from 'vite' import mockPlugin from 'vite-plugin-mock-dev-server' @@ -576,6 +594,7 @@ export default defineConfig({ See more examples: [example](/example/) **exp:** Match `/api/test`, And returns a response body content with empty data + ``` ts export default defineMock({ url: '/api/test', @@ -583,6 +602,7 @@ export default defineMock({ ``` **exp:** Match `/api/test` , And returns a static content data + ``` ts export default defineMock({ url: '/api/test', @@ -591,6 +611,7 @@ export default defineMock({ ``` **exp:** Only Support `GET` Method + ``` ts export default defineMock({ url: '/api/test', @@ -599,6 +620,7 @@ export default defineMock({ ``` **exp:** In the response header, add a custom header and cookie + ``` ts export default defineMock({ url: '/api/test', @@ -606,6 +628,7 @@ export default defineMock({ cookies: { 'my-cookie': '123456789' }, }) ``` + ``` ts export default defineMock({ url: '/api/test', @@ -619,6 +642,7 @@ export default defineMock({ ``` **exp:** Define multiple mock requests for the same URL and match valid rules with validators + ``` ts export default defineMock([ // Match /api/test?a=1 @@ -653,6 +677,7 @@ export default defineMock([ ``` **exp:** Response Delay + ``` ts export default defineMock({ url: '/api/test', @@ -661,6 +686,7 @@ export default defineMock({ ``` **exp:** The interface request failed + ``` ts export default defineMock({ url: '/api/test', @@ -670,6 +696,7 @@ export default defineMock({ ``` **exp:** Dynamic route matching + ``` ts export default defineMock({ url: '/api/user/:userId', @@ -682,6 +709,7 @@ export default defineMock({ The `userId` in the route will be resolved into the `request.params` object. **exp**:** Use the buffer to respond data + ```ts import { Buffer } from 'node:buffer' @@ -693,6 +721,7 @@ export default defineMock({ body: Buffer.from(JSON.stringify({ a: 1 })) }) ``` + ``` ts // When the type is buffer, the content-type is application/octet-stream. // The data passed in through body will be converted to a buffer. @@ -707,6 +736,7 @@ export default defineMock({ **exp:** Response file type Simulate file download, and pass in the file reading stream. + ``` ts import { createReadStream } from 'node:fs' @@ -717,11 +747,13 @@ export default defineMock({ body: () => createReadStream('./my-app.dmg') }) ``` + ```html Download File ``` **exp:** Use `mockjs`: + ``` ts import Mock from 'mockjs' @@ -734,9 +766,11 @@ export default defineMock({ }) }) ``` + You need install `mockjs` **exp:** Use `response` to customize the response + ``` ts export default defineMock({ url: '/api/test', @@ -756,6 +790,7 @@ export default defineMock({ ``` **exp:** Use json / json5 + ``` json { "url": "/api/test", @@ -768,6 +803,7 @@ export default defineMock({ **exp:** multipart, upload files. use [`formidable`](https://www.npmjs.com/package/formidable#readme) to support. + ``` html

@@ -785,6 +821,7 @@ use [`formidable`](https://www.npmjs.com/package/formidable#readme) to support. ``` fields `files` mapping to `formidable.File` + ``` ts export default defineMock({ url: '/api/upload', @@ -800,6 +837,7 @@ export default defineMock({ ``` **exp:** Graphql + ``` ts import { buildSchema, graphql } from 'graphql' @@ -829,6 +867,7 @@ fetch('/api/graphql', { ``` **exp:** WebSocket Mock + ``` ts // ws.mock.ts export default defineMock({ @@ -857,6 +896,7 @@ export default defineMock({ } }) ``` + ``` ts // app.ts const ws = new WebSocket('ws://localhost:5173/socket.io') @@ -878,6 +918,7 @@ In some scenarios, it may be necessary to use the data provided by mock services To meet such scenarios, on one hand, the plugin provides support under `vite preview`, and on the other hand, it also builds a small independent mock service application that can be deployed to relevant environments during `vite build`. This can then be forwarded through other HTTP servers like Nginx to actual ports for mock support. The default output is built into the directory `dist/mockServer`, generating files as follows: + ``` sh ./mockServer ├── index.js @@ -898,7 +939,7 @@ You can access related `mock` interfaces through `localhost:8080/`. ## Contributors -[![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors) diff --git a/README.zh-CN.md b/README.zh-CN.md index 779023a..9282e80 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -69,6 +69,7 @@ pnpm add -D vite-plugin-mock-dev-server ### 配置 `vite.config.ts` + ```ts import { defineConfig } from 'vite' import mockDevServerPlugin from 'vite-plugin-mock-dev-server' @@ -86,6 +87,7 @@ export default defineConfig({ } }) ``` + 插件会读取 `server.proxy` 或 `options.prefix` 的配置,对匹配的 url 启用mock 匹配。 插件也会读取 `define` 配置, 支持在 mock 文件中直接使用。 @@ -98,6 +100,7 @@ export default defineConfig({ 默认配置,在你的项目根目录的 `mock` 目录中编写mock数据: `mock/**/*.mock.ts` : + ```ts import { defineMock } from 'vite-plugin-mock-dev-server' @@ -114,6 +117,7 @@ export default defineMock({ vite plugin `vite.config.ts` + ```ts import { defineConfig } from 'vite' import mockDevServerPlugin from 'vite-plugin-mock-dev-server' @@ -192,6 +196,7 @@ export default defineConfig({ **默认值:** `{}` 示例: 配置文件上传的存放目录 + ```ts MockDevServerPlugin({ formidableOptions: { @@ -199,12 +204,17 @@ export default defineConfig({ } }) ``` + - `options.cookiesOptions` 配置 `cookies`, 查看 [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options) **默认值:** `{}` +- `options.bodyParserOptions` + + 配置 `co-body`, 查看 [co-body](https://github.com/cojs/co-body#options) + - `options.build` 需要构建可独立部署的小型mock服务时配置。 @@ -397,6 +407,7 @@ export default defineMock({ }, }) ``` + ```ts // 配置 WebSocket mock export default defineMock({ @@ -481,8 +492,10 @@ type defineMockData = ( ) => [getter, setter] & { value: T } ``` -#### 用法: +### 用法 + `data.ts` + ```ts import { defineMockData } from 'vite-plugin-mock-dev-server' @@ -491,7 +504,9 @@ export default defineMockData('posts', [ { id: '2', title: 'title2', content: 'content2' }, ]) ``` + `*.mock.ts` + ```ts import { defineMock } from 'vite-plugin-mock-dev-server' import posts from './data' @@ -525,6 +540,7 @@ export default defineMock([ 可以使用 `priority` 参数。 示例: + ```ts import { defineConfig } from 'vite' import mockPlugin from 'vite-plugin-mock-dev-server' @@ -557,7 +573,7 @@ export default defineConfig({ > **注意:** > -> `priority` 虽然可以调整优先级,但大多数时候,你都没有必要这么做。 +> `priority` 虽然可以调整优先级,但大多数时候,你都没有必要这么做。 > 对于一些特殊情况的请求,可以使用 静态规则来替代 `priority`,静态规则总是拥有最高优先级。 ## Example @@ -567,6 +583,7 @@ export default defineConfig({ 查看更多示例: [example](/example/) **exp:** 命中 `/api/test` 请求,并返回一个 数据为空的响应体内容 + ```ts export default defineMock({ url: '/api/test', @@ -574,12 +591,14 @@ export default defineMock({ ``` **exp:** 命中 `/api/test` 请求,并返回一个固定内容数据 + ```ts export default defineMock({ url: '/api/test', body: { a: 1 }, }) ``` + ```ts export default defineMock({ url: '/api/test', @@ -588,6 +607,7 @@ export default defineMock({ ``` **exp:** 限定只允许 `GET` 请求 + ```ts export default defineMock({ url: '/api/test', @@ -596,6 +616,7 @@ export default defineMock({ ``` **exp:** 在返回的响应头中,添加自定义 header 和 cookie + ```ts export default defineMock({ url: '/api/test', @@ -603,6 +624,7 @@ export default defineMock({ cookies: { 'my-cookie': '123456789' }, }) ``` + ```ts export default defineMock({ url: '/api/test', @@ -616,6 +638,7 @@ export default defineMock({ ``` **exp:** 定义多个相同url请求mock,并使用验证器匹配生效规则 + ```ts export default defineMock([ // 命中 /api/test?a=1 @@ -649,6 +672,7 @@ export default defineMock([ ``` **exp:** 延迟接口响应: + ```ts export default defineMock({ url: '/api/test', @@ -657,6 +681,7 @@ export default defineMock({ ``` **exp:** 使接口请求失败 + ```ts export default defineMock({ url: '/api/test', @@ -666,6 +691,7 @@ export default defineMock({ ``` **exp:** 动态路由匹配 + ```ts export default defineMock({ url: '/api/user/:userId', @@ -678,6 +704,7 @@ export default defineMock({ 路由中的 `userId`将会解析到 `request.params` 对象中. **exp:** 使用 buffer 响应数据 + ```ts import { Buffer } from 'node:buffer' @@ -688,6 +715,7 @@ export default defineMock({ body: Buffer.from(JSON.stringify({ a: 1 })) }) ``` + ```ts // 当 type 为 buffer 时,content-type 为 application/octet-stream, // body 传入的数据会被转为 buffer @@ -702,6 +730,7 @@ export default defineMock({ **exp:** 响应文件类型 模拟文件下载,传入文件读取流 + ```ts import { createReadStream } from 'node:fs' @@ -712,11 +741,13 @@ export default defineMock({ body: () => createReadStream('./my-app.dmg') }) ``` + ```html 下载文件 ``` **exp:** 使用 `mockjs` 生成响应数据: + ```ts import Mock from 'mockjs' @@ -729,9 +760,11 @@ export default defineMock({ }) }) ``` + 请先安装 `mockjs` **exp:** 使用 `response` 自定义响应 + ```ts export default defineMock({ url: '/api/test', @@ -751,6 +784,7 @@ export default defineMock({ ``` **exp:** 使用 json / json5 + ```json { "url": "/api/test", @@ -763,6 +797,7 @@ export default defineMock({ **exp:** multipart, 文件上传. 通过 [`formidable`](https://www.npmjs.com/package/formidable#readme) 支持。 + ``` html

@@ -780,6 +815,7 @@ export default defineMock({ ``` fields `files` 映射为 `formidable.File` 类型。 + ``` ts export default defineMock({ url: '/api/upload', @@ -795,6 +831,7 @@ export default defineMock({ ``` **exp:** Graphql + ```ts import { buildSchema, graphql } from 'graphql' @@ -824,6 +861,7 @@ fetch('/api/graphql', { ``` **exp:** WebSocket Mock + ```ts // ws.mock.ts export default defineMock({ @@ -852,6 +890,7 @@ export default defineMock({ } }) ``` + ```ts // app.ts const ws = new WebSocket('ws://localhost:5173/socket.io') @@ -873,6 +912,7 @@ ws.addEventListener('message', (raw) => { 为了能够满足这类场景,插件一方面提供了 `vite preview` 下的支持,同时还提供了在 `vite build` 时,也构建一个可独立部署的 小型mock服务应用,可以将这个应用部署到相关的环境,后通过其他http服务器如nginx做代理转发到实际端口实现mock支持。 构建默认输出到 `dist/mockServer` 目录中,并生成如下文件: + ```sh ./mockServer ├── index.js diff --git a/docs/en/examples/faker.md b/docs/en/examples/faker.md index 171721b..9f284e6 100644 --- a/docs/en/examples/faker.md +++ b/docs/en/examples/faker.md @@ -4,9 +4,11 @@ Generate mock data using the `faker-js` library. ::: tip You need to manually install the `faker-js` library + ```sh pnpm add -D @faker-js/faker ``` + ::: ```ts diff --git a/docs/en/examples/file.md b/docs/en/examples/file.md index ea1a61e..4d87463 100644 --- a/docs/en/examples/file.md +++ b/docs/en/examples/file.md @@ -19,6 +19,7 @@ Form Upload File ``` ::: code-group + ```ts [upload.mock.ts] export default defineMock({ url: '/api/upload', @@ -32,6 +33,7 @@ export default defineMock({ }, }) ``` + ::: ## File Download diff --git a/docs/en/examples/format-extension.md b/docs/en/examples/format-extension.md index fd7d31d..bbb1575 100644 --- a/docs/en/examples/format-extension.md +++ b/docs/en/examples/format-extension.md @@ -18,6 +18,7 @@ Write mock files using ESModule ::: ::: code-group + ``` js [api.mock.mjs] /** * @type {import('vite-plugin-mock-dev-server').MockOptions} @@ -33,6 +34,7 @@ export default [ } ] ``` + ```ts [api.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' @@ -47,6 +49,7 @@ export default defineMock([ } ]) ``` + ::: ## JSON diff --git a/docs/en/examples/graphql.md b/docs/en/examples/graphql.md index 80c4a30..b07c0ff 100644 --- a/docs/en/examples/graphql.md +++ b/docs/en/examples/graphql.md @@ -3,6 +3,7 @@ You need to install `graphql`. ::: code-group + ```ts [graphql.mock.ts] import { buildSchema, graphql } from 'graphql' @@ -23,9 +24,11 @@ export default defineMock({ }, }) ``` + ::: ::: code-group + ```ts [api.ts] const response = await fetch('/api/graphql', { method: 'POST', @@ -35,4 +38,5 @@ if (response.ok) { const data = await response.json() } ``` + ::: diff --git a/docs/en/examples/header.md b/docs/en/examples/header.md index 9e78f4a..95063a3 100644 --- a/docs/en/examples/header.md +++ b/docs/en/examples/header.md @@ -3,6 +3,7 @@ Example, simulate adding JWT, Authorization Header ## Object Type + ```ts import { defineMock } from 'vite-plugin-mock-dev-server' diff --git a/docs/en/examples/mockjs.md b/docs/en/examples/mockjs.md index d3709ac..d5d2d4e 100644 --- a/docs/en/examples/mockjs.md +++ b/docs/en/examples/mockjs.md @@ -4,9 +4,11 @@ Generate mock data using the `mockjs` library. ::: tip You need to manually install the `mockjs` library . + ```sh pnpm add -D mockjs ``` + ::: ```ts diff --git a/docs/en/examples/validator.md b/docs/en/examples/validator.md index 4dff52b..58e528b 100644 --- a/docs/en/examples/validator.md +++ b/docs/en/examples/validator.md @@ -44,6 +44,7 @@ For the request body, which may have a relatively complex data structure, deep v The plugin supports checking if the body configured in the validator is a subset of the request body. ::: code-group + ``` ts [api.mock.ts] export default defineMock({ url: '/mock/validator-body', @@ -56,6 +57,7 @@ export default defineMock({ body: '' }) ``` + ``` ts [fetch.ts] await fetch('/mock/validator-body', { method: 'POST', @@ -66,6 +68,7 @@ await fetch('/mock/validator-body', { }) }) ``` + ::: ::: info diff --git a/docs/en/examples/websocket.md b/docs/en/examples/websocket.md index f69428f..2f80c54 100644 --- a/docs/en/examples/websocket.md +++ b/docs/en/examples/websocket.md @@ -1,11 +1,13 @@ # WebSocket ## Basic Usage + <<< @/../example/mock/ws.mock.ts ## Simulated Real-time Push ::: code-group + ```ts [ws-real-time-push.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' @@ -27,11 +29,13 @@ export default defineMock({ } }) ``` + ::: ## Simulated Chat Room ::: code-group + ```ts [ws-chat.mock.ts] import type { MockRequest } from 'vite-plugin-mock-dev-server' import { defineMock } from 'vite-plugin-mock-dev-server' @@ -82,9 +86,11 @@ export default defineMock({ } }) ``` + ::: ::: code-group + ```ts [app.ts] const store = { userList: [], @@ -122,4 +128,5 @@ function closeChat() { ws.close() } ``` + ::: diff --git a/docs/en/guide/define-mock-data.md b/docs/en/guide/define-mock-data.md index 169ef94..1d543de 100644 --- a/docs/en/guide/define-mock-data.md +++ b/docs/en/guide/define-mock-data.md @@ -36,6 +36,7 @@ export const posts = defineMockData('posts', [ { id: '2', title: 'title2', content: 'content2' }, ]) ``` + The data encapsulated by `defineMockData` provides two different styles of data reading and writing support through the plugin, satisfying the usage habits of different developers. - `posts.value`: Use `Object.defineProperty` to define read and write data. @@ -43,6 +44,7 @@ The data encapsulated by `defineMockData` provides two different styles of data `*.mock.ts` (`.value`) ::: code-group + ```ts [post-list.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from './data' @@ -52,6 +54,7 @@ export default defineMock({ body: () => posts.value }) ``` + ```ts [post-delete.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from './data' @@ -65,10 +68,12 @@ export default defineMock({ } }) ``` + ::: `*.mock.ts` (`[getter, setter]`) ::: code-group + ```ts [post-list.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from './data' @@ -81,6 +86,7 @@ export default defineMock({ } }) ``` + ```ts [post-delete.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from './data' @@ -97,4 +103,5 @@ export default defineMock({ } }) ``` + ::: diff --git a/docs/en/guide/file-management.md b/docs/en/guide/file-management.md index 131bff5..94ccafa 100644 --- a/docs/en/guide/file-management.md +++ b/docs/en/guide/file-management.md @@ -8,6 +8,7 @@ Microservices architecture is the mainstream architecture used by backend servic In this scenario, in order to have a clear mapping relationship with the backend microservices architecture, we should also use a directory structure in the `mock` directory to manage and organize the mocks. For example, in an e-commerce project, the backend provides: + - **Goods service**: Provides interfaces such as product list and product details. - **Search service**: Provides interfaces such as keyword search and filtering. - **Order service**: Provides interfaces such as order list and order details. diff --git a/docs/en/guide/mock-config.md b/docs/en/guide/mock-config.md index 5c336b0..87c2049 100644 --- a/docs/en/guide/mock-config.md +++ b/docs/en/guide/mock-config.md @@ -11,7 +11,8 @@ export default defineMock({ }) ``` -**Type Definition** +**Type Definition:** + ```ts interface RequestOptions { query: Record // query string parse @@ -22,7 +23,7 @@ interface RequestOptions { } ``` -**Description** +**Description:** ::: warning If using json/json5 to write mock files, the `response` method is not supported, nor is the use of other field functions. @@ -179,6 +180,7 @@ Don't forget to use `res.end()` to return the response body data, or use `next() ## validator - **Type**: `Validator` | `ValidatorFn` + ```ts interface Validator { header?: object @@ -191,6 +193,7 @@ Don't forget to use `res.end()` to return the response body data, or use `next() (request: RequestOptions): boolean } ``` + - **Optional** - **Default**: `null` diff --git a/docs/en/guide/plugin-config.md b/docs/en/guide/plugin-config.md index af63dc2..97bf966 100644 --- a/docs/en/guide/plugin-config.md +++ b/docs/en/guide/plugin-config.md @@ -18,13 +18,15 @@ export default defineConfig({ cors: true, formidableOptions: undefined, cookiesOptions: undefined, + bodyParserOptions: undefined, priority: undefined }), ] }) ``` -**Type** +**Type:** + ``` ts interface MockServerPluginOptions { prefix?: string | string[] @@ -132,6 +134,16 @@ Configure `cookies` For detailed configuration, refer to [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options). +## bodyParserOptions + +**Type**: `coBody.Options & { formLimit?: string | number, jsonLimit?: string | number, textLimit?: string | number }` + +**Default**: `undefined` + +Configure `co-body` + +For detailed configuration, refer to [co-body](https://github.com/cojs/co-body#options). + ## build **Type**: `boolean | ServerBuildOption` diff --git a/docs/en/guide/shared-data.md b/docs/en/guide/shared-data.md index 418dfb9..a9bc40f 100644 --- a/docs/en/guide/shared-data.md +++ b/docs/en/guide/shared-data.md @@ -12,6 +12,7 @@ const posts = [ { id: 2, title: 'post2', content: '', author: 'John' }, ] ``` + - `/api/post/delete/:id` Delete a post - `/api/post/update/:id` Update a post - `/api/post/list` Get a list of all posts @@ -21,6 +22,7 @@ I expect that after calling the delete and update post APIs, the get all posts A If the data operations are relatively simple, we can write the data and mock request configuration in the same `*.mock.ts` file. ::: code-group + ```ts [*.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' @@ -52,11 +54,13 @@ export default defineMock([ } ]) ``` + ::: And if we need to manage complex scenarios, we may need to break it down into different files: ::: code-group + ```ts [posts/list.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -66,6 +70,7 @@ export default defineMock({ body: () => posts }) ``` + ```ts [posts/update.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -79,6 +84,7 @@ export default defineMock({ } }) ``` + ```ts [posts/delete.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -92,12 +98,14 @@ export default defineMock({ } }) ``` + ```ts [shared/data.ts] export const posts = [ { id: 1, title: 'post1', content: '', author: 'Mark' }, { id: 2, title: 'post2', content: '', author: 'John' }, ] ``` + ::: At this point, the interface will not return the modified data as expected. This is because each `*.mock.ts` file is independently importing `data.ts` for separate compilation. @@ -112,6 +120,7 @@ To address this, the plugin provides a `defineMockData(key, initialData)` functi You just need to wrap the data in `data.ts` with `defineMockData`. ::: code-group + ```ts [shared/data.ts] {1,3} import { defineMockData } from 'vite-plugin-mock-dev-server' @@ -120,6 +129,7 @@ export const posts = defineMockData('posts', [ { id: 2, title: 'post2', content: '', author: 'John' }, ]) ``` + ```ts [posts/list.mock.ts] {6} import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -129,6 +139,7 @@ export default defineMock({ body: () => posts.value }) ``` + ```ts [posts/update.mock.ts] {7,8} import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -142,6 +153,7 @@ export default defineMock({ } }) ``` + ```ts [posts/delete.mock.ts] {7,8} import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -155,6 +167,7 @@ export default defineMock({ } }) ``` + ::: `defineMockData` isolates the data into a separate shared scope and ensures the uniqueness of the data through a `key`. diff --git a/docs/en/guide/shared.md b/docs/en/guide/shared.md index 0582c66..dd83905 100644 --- a/docs/en/guide/shared.md +++ b/docs/en/guide/shared.md @@ -22,6 +22,7 @@ It is recommended to create a `/mock/shared` directory in the `/mock` directory For example, provide a wrapper function that returns data and a user data file. ::: code-group + ``` ts [shared/utils/dataWrap.ts] export function successWrap(data) { return { @@ -31,6 +32,7 @@ export function successWrap(data) { } } ``` + ```ts [shared/database/user.ts] export const userMap = { Mark: { @@ -43,6 +45,7 @@ export const userMap = { } } ``` + ```ts [user/info.mock.ts] import { userMap } from '../shared/database/user' import { successWrap } from '../shared/utils/dataWrap' @@ -56,4 +59,5 @@ export default defineMock({ } }) ``` + ::: diff --git a/docs/en/guide/teamwork.md b/docs/en/guide/teamwork.md index 73de8b8..dda8c19 100644 --- a/docs/en/guide/teamwork.md +++ b/docs/en/guide/teamwork.md @@ -44,6 +44,7 @@ export default defineMock({ } }) ``` + The `/api/demo` interface will only respond to requests that have the `?a=1` query parameter in the referring source address, such as `http://example.com/?a=1`. Therefore, we can split the mock files based on `refererQuery` and refine the file management according to the team's specified collaboration guidelines. diff --git a/docs/en/guide/upload.md b/docs/en/guide/upload.md index 0d6f038..c6805c2 100644 --- a/docs/en/guide/upload.md +++ b/docs/en/guide/upload.md @@ -31,6 +31,7 @@ In the data fields of form submissions, such as the form field `files`, it is pa If the `multiple` attribute is declared, the corresponding field is parsed as an array of `formidable.File`. ::: code-group + ```ts [formidable.File] interface File { /** @@ -85,6 +86,7 @@ interface File { toString: () => string } ``` + ::: In the mock configuration file, you can directly access the relevant information using `req.body.*`: diff --git a/docs/en/guide/usage.md b/docs/en/guide/usage.md index 0ef0e2a..1f44cd6 100644 --- a/docs/en/guide/usage.md +++ b/docs/en/guide/usage.md @@ -9,6 +9,7 @@ If you haven't installed this plugin in your project yet, please refer to [Insta In your project's `vite.config.{ts,js}` file, import and configure the plugin: ::: code-group + ``` ts [typescript] import { defineConfig } from 'vite' @@ -20,6 +21,7 @@ export default defineConfig({ ], }) ``` + ``` js [javascript] const mockDevServerPlugin = require('vite-plugin-mock-dev-server') // [!code ++] /** @@ -31,6 +33,7 @@ module.exports = { ], } ``` + ::: ## Step2: Configure `server.proxy` @@ -40,6 +43,7 @@ The plugin directly reads the request path prefix configured in `server.proxy` a In general scenarios, when configuring the `server.proxy` proxy forwarding configuration in the development environment, it directly forwards to the development environment address of the backend service. When the backend service has not completed the interface development but has provided the interface documentation, we only need to mock this part of the interface to enable parallel development of the frontend interface integration process. Therefore, this plugin directly reads the `server.proxy` configuration to reduce the complexity of plugin configuration. ::: code-group + ``` ts [typescript] import { defineConfig } from 'vite' import mockDevServerPlugin from 'vite-plugin-mock-dev-server' @@ -55,6 +59,7 @@ export default defineConfig({ }, // [!code ++] }) ``` + ``` js [javascript] const mockDevServerPlugin = require('vite-plugin-mock-dev-server') @@ -72,6 +77,7 @@ module.exports = { }, // [!code ++] } ``` + ::: ## Step3: Add `/mock` directory @@ -117,6 +123,7 @@ Add `*.mock.ts` files: The plugin provides the `defineMock()` function to help write mock configurations. ::: code-group + ```ts [api.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' @@ -125,6 +132,7 @@ export default defineMock({ body: {} }) ``` + ::: ## Step5: Start Vite Development Server diff --git a/docs/examples/faker.md b/docs/examples/faker.md index 32a2d77..9498b23 100644 --- a/docs/examples/faker.md +++ b/docs/examples/faker.md @@ -4,9 +4,11 @@ ::: tip 你需要自行安装 `faker-js` 库 + ```sh pnpm add -D @faker-js/faker ``` + ::: ```ts diff --git a/docs/examples/file.md b/docs/examples/file.md index 0b8d177..e5287a0 100644 --- a/docs/examples/file.md +++ b/docs/examples/file.md @@ -19,6 +19,7 @@ ``` ::: code-group + ```ts [upload.mock.ts] export default defineMock({ url: '/api/upload', @@ -32,11 +33,13 @@ export default defineMock({ }, }) ``` + ::: ## 文件下载 模拟文件下载,传入文件读取流 + ```ts import { createReadStream } from 'node:fs' diff --git a/docs/examples/format-extension.md b/docs/examples/format-extension.md index bf5db4e..c5a0f79 100644 --- a/docs/examples/format-extension.md +++ b/docs/examples/format-extension.md @@ -18,6 +18,7 @@ ::: ::: code-group + ``` js [api.mock.mjs] /** * @type {import('vite-plugin-mock-dev-server').MockOptions} @@ -33,6 +34,7 @@ export default [ } ] ``` + ```ts [api.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' @@ -47,6 +49,7 @@ export default defineMock([ } ]) ``` + ::: ## JSON diff --git a/docs/examples/graphql.md b/docs/examples/graphql.md index b84d24b..6846a4e 100644 --- a/docs/examples/graphql.md +++ b/docs/examples/graphql.md @@ -3,6 +3,7 @@ 需要安装 `graphql`。 ::: code-group + ```ts [graphql.mock.ts] import { buildSchema, graphql } from 'graphql' @@ -23,9 +24,11 @@ export default defineMock({ }, }) ``` + ::: ::: code-group + ```ts [api.ts] const response = await fetch('/api/graphql', { method: 'POST', @@ -35,4 +38,5 @@ if (response.ok) { const data = await response.json() } ``` + ::: diff --git a/docs/examples/header.md b/docs/examples/header.md index 81780e0..292ee8d 100644 --- a/docs/examples/header.md +++ b/docs/examples/header.md @@ -5,6 +5,7 @@ 示例,模拟添加 JWT, Authorization Header ## 对象类型 + ```ts import { defineMock } from 'vite-plugin-mock-dev-server' diff --git a/docs/examples/mockjs.md b/docs/examples/mockjs.md index 967de6a..9f49230 100644 --- a/docs/examples/mockjs.md +++ b/docs/examples/mockjs.md @@ -4,9 +4,11 @@ ::: tip 你需要自行安装 `mockjs` 库 + ```sh pnpm add -D mockjs ``` + ::: ```ts diff --git a/docs/examples/validator.md b/docs/examples/validator.md index 0ac0e57..32489b6 100644 --- a/docs/examples/validator.md +++ b/docs/examples/validator.md @@ -45,6 +45,7 @@ 插件支持判断 验证器配置的 body 是否 属于 请求体 body 的 子集。 ::: code-group + ``` ts [api.mock.ts] export default defineMock({ url: '/mock/validator-body', @@ -57,6 +58,7 @@ export default defineMock({ body: '' }) ``` + ``` ts [fetch.ts] await fetch('/mock/validator-body', { method: 'POST', @@ -67,6 +69,7 @@ await fetch('/mock/validator-body', { }) }) ``` + ::: ::: info diff --git a/docs/examples/websocket.md b/docs/examples/websocket.md index 346d0e2..74d62bf 100644 --- a/docs/examples/websocket.md +++ b/docs/examples/websocket.md @@ -1,11 +1,13 @@ # WebSocket ## 基础示例 + <<< @/../example/mock/ws.mock.ts ## 模拟实时推送 ::: code-group + ```ts [ws-real-time-push.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' @@ -27,11 +29,13 @@ export default defineMock({ } }) ``` + ::: ## 模拟聊天室 ::: code-group + ```ts [ws-chat.mock.ts] import type { MockRequest } from 'vite-plugin-mock-dev-server' import { defineMock } from 'vite-plugin-mock-dev-server' @@ -82,9 +86,11 @@ export default defineMock({ } }) ``` + ::: ::: code-group + ```ts [app.ts] const store = { userList: [], @@ -122,4 +128,5 @@ function closeChat() { ws.close() } ``` + ::: diff --git a/docs/guide/define-mock-data.md b/docs/guide/define-mock-data.md index 6508c93..1c46447 100644 --- a/docs/guide/define-mock-data.md +++ b/docs/guide/define-mock-data.md @@ -45,6 +45,7 @@ export const posts = defineMockData('posts', [ `*.mock.ts` (`.value`) ::: code-group + ```ts [post-list.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from './data' @@ -54,6 +55,7 @@ export default defineMock({ body: () => posts.value }) ``` + ```ts [post-delete.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from './data' @@ -67,10 +69,12 @@ export default defineMock({ } }) ``` + ::: `*.mock.ts` (`[getter, setter]`) ::: code-group + ```ts [post-list.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from './data' @@ -83,6 +87,7 @@ export default defineMock({ } }) ``` + ```ts [post-delete.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from './data' @@ -99,4 +104,5 @@ export default defineMock({ } }) ``` + ::: diff --git a/docs/guide/define-mock.md b/docs/guide/define-mock.md index 853058a..b20fd9d 100644 --- a/docs/guide/define-mock.md +++ b/docs/guide/define-mock.md @@ -14,6 +14,7 @@ export default defineMock({ ``` 传入数组: + ```ts import { defineMock } from 'vite-plugin-mock-dev-server' diff --git a/docs/guide/file-management.md b/docs/guide/file-management.md index 3a75e26..b8d20a0 100644 --- a/docs/guide/file-management.md +++ b/docs/guide/file-management.md @@ -9,6 +9,7 @@ 划分目录进行管理。 比如,在一个 电商类的项目中, 后端提供了: + - **商品服务**:提供了 商品列表、商品详情 等接口; - **搜索服务**:提供了 关键字搜索、条件筛选 等接口; - **订单服务**:提供了 订单列表、订单详情 等接口; @@ -70,6 +71,7 @@ export default defineMock([ ``` 又或者,数组的形式不能够使开发者清晰的区分差异,那么也可以通过 具名变量导出的方式,在同一个mock文件中处理: + ```ts export const appleGoods = defineMock({ url: 'api/goods/detail', diff --git a/docs/guide/mock-config.md b/docs/guide/mock-config.md index 41bb8d0..2382e9d 100644 --- a/docs/guide/mock-config.md +++ b/docs/guide/mock-config.md @@ -11,7 +11,8 @@ export default defineMock({ }) ``` -**类型定义** +**类型定义:** + ```ts // 请求接口包含的信息 interface RequestOptions { @@ -23,7 +24,7 @@ interface RequestOptions { } ``` -**注意** +**注意:** ::: warning 如果使用 json/json5 编写 mock文件,则不支持使用 response 方法,以及不支持使用其他字段的函数形式。 @@ -180,6 +181,7 @@ type ResponseBody = string | number | array | object | Buffer | ReadableStream ## validator - **Type**: `Validator` | `ValidatorFn` + ```ts interface Validator { header?: object @@ -192,6 +194,7 @@ type ResponseBody = string | number | array | object | Buffer | ReadableStream (request: RequestOptions): boolean } ``` + - **选填** - **默认值**: `null` diff --git a/docs/guide/mock-service.md b/docs/guide/mock-service.md index 9b84531..8808dff 100644 --- a/docs/guide/mock-service.md +++ b/docs/guide/mock-service.md @@ -5,6 +5,7 @@ 为了能够满足这类场景,插件一方面提供了 `vite preview` 下的支持,同时还提供了在 `vite build` 时,也构建一个可独立部署的 小型mock服务应用,可以将这个应用部署到相关的环境,后通过其他http服务器如nginx做代理转发到实际端口实现mock支持。 构建默认输出到 `dist/mockServer` 目录中,并生成如下文件: + ```sh ./mockServer ├── index.js diff --git a/docs/guide/plugin-config.md b/docs/guide/plugin-config.md index 4d7e269..7077458 100644 --- a/docs/guide/plugin-config.md +++ b/docs/guide/plugin-config.md @@ -18,13 +18,15 @@ export default defineConfig({ cors: true, formidableOptions: undefined, cookiesOptions: undefined, + bodyParserOptions: undefined, priority: undefined }), ] }) ``` -**Type** +**Type:** + ``` ts interface MockServerPluginOptions { prefix?: string | string[] @@ -36,6 +38,11 @@ interface MockServerPluginOptions { cors?: boolean | CorsOptions formidableOptions?: formidable.Options cookiesOptions?: Cookies.Option + bodyParserOptions?: coBody.Options & { + formLimit?: string | number + jsonLimit?: string | number + textLimit?: string | number + } build?: boolean | ServerBuildOption priority?: MockMatchPriority } @@ -131,6 +138,16 @@ mock资源热更新时,仅更新了数据内容,但是默认不重新刷新 详细配置信息查看 [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options) +## bodyParserOptions + +**类型**: `coBody.Options & { formLimit?: string | number, jsonLimit?: string | number, textLimit?: string | number }` + +**默认值**: `undefined` + +配置 `co-body` + +详细配置信息查看 [co-body](https://github.com/cojs/co-body#options) + ## build **类型**: `boolean | ServerBuildOption` diff --git a/docs/guide/shared-data.md b/docs/guide/shared-data.md index d921370..81ad41d 100644 --- a/docs/guide/shared-data.md +++ b/docs/guide/shared-data.md @@ -8,12 +8,14 @@ 对于一些复杂场景,期望 接口 B 返回被 接口 A 修改过的数据,比如: 模拟 对 文章列表和文章的修改: + ```ts const posts = [ { id: 1, title: 'post1', content: '', author: 'Mark' }, { id: 2, title: 'post2', content: '', author: 'John' }, ] ``` + - `/api/post/delete/:id` 将会删除文章, - `/api/post/update/:id` 用于修改文章, - `/api/post/list` 获取所有文章列表 @@ -23,6 +25,7 @@ const posts = [ 如果对数据的操作比较简单,我们可以将 数据、模拟请求配置都放在 同一个 `*.mock.ts` 中编写: ::: code-group + ```ts [*.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' @@ -54,10 +57,12 @@ export default defineMock([ } ]) ``` + ::: 而如果对于复杂场景,我们可能需要拆解为不同的文件来进行管理时: ::: code-group + ```ts [posts/list.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -67,6 +72,7 @@ export default defineMock({ body: () => posts }) ``` + ```ts [posts/update.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -80,6 +86,7 @@ export default defineMock({ } }) ``` + ```ts [posts/delete.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -93,12 +100,14 @@ export default defineMock({ } }) ``` + ```ts [shared/data.ts] export const posts = [ { id: 1, title: 'post1', content: '', author: 'Mark' }, { id: 2, title: 'post2', content: '', author: 'John' }, ] ``` + ::: 这时候,接口将不会按预期返回被修改的数据,这是由于每个 `*.mock.ts` 都是独立引入 `data.ts`进行单独编译的。 @@ -113,6 +122,7 @@ export const posts = [ 只需要将 `data.ts` 中的数据包装在 `defineMockData` 中即可。 ::: code-group + ```ts [shared/data.ts] {1,3} import { defineMockData } from 'vite-plugin-mock-dev-server' @@ -121,6 +131,7 @@ export const posts = defineMockData('posts', [ { id: 2, title: 'post2', content: '', author: 'John' }, ]) ``` + ```ts [posts/list.mock.ts] {6} import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -130,6 +141,7 @@ export default defineMock({ body: () => posts.value }) ``` + ```ts [posts/update.mock.ts] {7,8} import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -143,6 +155,7 @@ export default defineMock({ } }) ``` + ```ts [posts/delete.mock.ts] {7,8} import { defineMock } from 'vite-plugin-mock-dev-server' import { posts } from '../shared/data' @@ -156,6 +169,7 @@ export default defineMock({ } }) ``` + ::: `defineMockData` 将数据隔离到单独的共享作用域中,并通过 `key` 保证数据的唯一性。 diff --git a/docs/guide/shared.md b/docs/guide/shared.md index e787608..1a0998c 100644 --- a/docs/guide/shared.md +++ b/docs/guide/shared.md @@ -24,6 +24,7 @@ 比如,提供一个 返回数据的包装函数,和一个 用户数据文件 ::: code-group + ``` ts [shared/utils/dataWrap.ts] export function successWrap(data) { return { @@ -33,6 +34,7 @@ export function successWrap(data) { } } ``` + ```ts [shared/database/user.ts] export const userMap = { Mark: { @@ -45,6 +47,7 @@ export const userMap = { } } ``` + ```ts [user/info.mock.ts] import { userMap } from '../shared/database/user' import { successWrap } from '../shared/utils/dataWrap' @@ -58,4 +61,5 @@ export default defineMock({ } }) ``` + ::: diff --git a/docs/guide/teamwork.md b/docs/guide/teamwork.md index 2013f13..55bd0f4 100644 --- a/docs/guide/teamwork.md +++ b/docs/guide/teamwork.md @@ -26,9 +26,10 @@ 那么,选择使用发起 mock api 的来源页地址来区分,是一种很好的方式,因为这种方式可以使我们直接在 浏览器地址栏中,直接修改地址即可区分返回不同的参数! -而发起 mock api 的来源页地址,也将会附带在 `mock request ` 的 `referer` 字段上,所以插件内可以通过解析 `referer` 来实现 一个新的 `validator` 。 +而发起 mock api 的来源页地址,也将会附带在 `mock request` 的 `referer` 字段上,所以插件内可以通过解析 `referer` 来实现 一个新的 `validator` 。 如以下配置: + ``` ts import { defineMock } from 'vite-plugin-mock-dev-server' @@ -44,6 +45,7 @@ export default defineMock({ } }) ``` + `/api/demo` 接口只会响应来自带了 `?a=1` 的请求来源地址,如 `http://example.com/?a=1`。 所以可以基于 `refererQuery`,进行 mock file 的拆分,根据 团队指定的协作规范,细化文件管理。 diff --git a/docs/guide/upload.md b/docs/guide/upload.md index fae2ce4..1884c11 100644 --- a/docs/guide/upload.md +++ b/docs/guide/upload.md @@ -33,6 +33,7 @@ fetch('/api/upload', { 如果 声明了 `multiple` 属性,则对应字段解析为 `formidable.File[]` 的数组。 ::: code-group + ```ts [formidable.File] interface File { /** @@ -87,9 +88,11 @@ interface File { toString: () => string } ``` + ::: 在mock 配置文件中, 可直接通过 `req.body.*` 获取相关的信息: + ```ts export default defineMock({ url: '/api/upload', diff --git a/docs/guide/usage.md b/docs/guide/usage.md index 212b3db..2f87233 100644 --- a/docs/guide/usage.md +++ b/docs/guide/usage.md @@ -7,6 +7,7 @@ 在你的项目的 `vite.config.{ts,js}`文件中,引入并配置插件: ::: code-group + ``` ts [typescript] import { defineConfig } from 'vite' @@ -18,6 +19,7 @@ export default defineConfig({ ], }) ``` + ``` js [javascript] const mockDevServerPlugin = require('vite-plugin-mock-dev-server') // [!code ++] /** @@ -29,6 +31,7 @@ module.exports = { ], } ``` + ::: ## Step2: 配置 `server.proxy` @@ -40,6 +43,7 @@ module.exports = { 因此,本插件直接读取 `server.proxy` 配置,从而减少插件需要配置的参数复杂度。 ::: code-group + ``` ts [typescript] import { defineConfig } from 'vite' import mockDevServerPlugin from 'vite-plugin-mock-dev-server' @@ -55,6 +59,7 @@ export default defineConfig({ }, // [!code ++] }) ``` + ``` js [javascript] const mockDevServerPlugin = require('vite-plugin-mock-dev-server') @@ -72,6 +77,7 @@ module.exports = { }, // [!code ++] } ``` + ::: ## Step3: 添加 `/mock` 目录 @@ -102,6 +108,7 @@ module.exports = { "cjs": [".cjs", ".cts"] } ``` + **`.js/.ts` 文件根据 `package.json` 的 `type` 字段值判断, 默认为 `cjs`。** 新增 `*.mock.ts` 文件: @@ -116,6 +123,7 @@ module.exports = { 插件提供了 [`defineMock()`](/guide/define-mock) 函数帮助编写 mock 配置。 ::: code-group + ```ts [api.mock.ts] import { defineMock } from 'vite-plugin-mock-dev-server' @@ -124,6 +132,7 @@ export default defineMock({ body: {} }) ``` + ::: ## Step5: 启动 Vite 开发服务