vite-plugin-mock-dev-server 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  <a href="https://www.npmjs.com/package/vite-plugin-mock-dev-server"><img alt="npm" src="https://img.shields.io/npm/v/vite-plugin-mock-dev-server?style=flat-square"></a>
12
12
  <img alt="node-current" src="https://img.shields.io/node/v/vite-plugin-mock-dev-server?style=flat-square">
13
13
  <img alt="npm peer dependency version" src="https://img.shields.io/npm/dependency-version/vite-plugin-mock-dev-server/peer/vite?style=flat-square">
14
- <img alt="npm" src="https://img.shields.io/npm/dm/vite-plugin-mock-dev-server?style=flat-square">
14
+ <img alt="npm" src="https://img.shields.io/npm/dt/vite-plugin-mock-dev-server?style=flat-square">
15
15
  <br>
16
16
  <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pengzhanbo/vite-plugin-mock-dev-server/lint.yml?style=flat-square">
17
17
  <a href="https://app.fossa.com/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server?ref=badge_shield"><img alt="fossa status" src="https://app.fossa.com/api/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server.svg?type=shield"></a>
@@ -43,6 +43,7 @@
43
43
  - 🌈 Support `vite preview` mode.
44
44
  - 📤 Support `multipart` content-type,mock upload file.
45
45
  - 📥 Support mock download file.
46
+ - ⚜️ Support `WebSocket Mock`
46
47
  - 🗂 Support building small independent deployable mock services.
47
48
 
48
49
 
@@ -148,6 +149,18 @@ export default defineConfig({
148
149
 
149
150
  **Default:** `[]`
150
151
 
152
+ - `options.wsPrefix`
153
+
154
+ **类型:** `string | string[]`
155
+
156
+ Configure the matching rules for WebSocket service. Any request path starting with the value of `wsPrefix` and using the `ws/wss` protocol will be proxied to the corresponding target.
157
+
158
+ If the value of `wsPrefix` starts with `^`, it will be recognized as a RegExp.
159
+
160
+ > Different from using `viteConfig.server.proxy` by default for http mock, `websocket mock` does not use the ws-related configuration in `viteConfig.server.proxy`. Also, rules configured in `wsPrefix` cannot be configured simultaneously in `viteConfig.server.proxy`, as it will cause conflicts when starting the vite server because multiple instances of WebSocketServer cannot be implemented for the same request.
161
+ > This conflict is neither a problem with Vite nor with the plugin; it belongs to a reasonable error type. When switching between WebSocket Mock and WebSocket Proxy, please pay attention to avoid duplicate configurations that may cause conflicts.
162
+
163
+
151
164
  - `option.include`
152
165
 
153
166
  **Type:** `string | string[]`
@@ -162,14 +175,7 @@ export default defineConfig({
162
175
 
163
176
  When reading mock files for configuration, the files that need to be excluded can be a directory, glob, or an array.
164
177
 
165
- **Default:**
166
- ```ts
167
- [
168
- '**/node_modules/**',
169
- '**/.vscode/**',
170
- '**/.git/**',
171
- ]
172
- ```
178
+ **Default:** `['**/node_modules/**','**/.vscode/**','**/.git/**']`
173
179
 
174
180
  - `options.reload`
175
181
 
@@ -258,6 +264,7 @@ export default defineApiMock({
258
264
  ## Mock Configuration
259
265
 
260
266
  ```ts
267
+ // Configure the http mock
261
268
  export default defineMock({
262
269
  /**
263
270
  * Request address, supports the `/api/user/:id` format.
@@ -380,7 +387,32 @@ export default defineMock({
380
387
  res.end()
381
388
  }
382
389
  })
383
-
390
+ ```
391
+ ```ts
392
+ // Configure the WebSocket mock
393
+ export default defineMock({
394
+ /**
395
+ * Request address, supports the `/api/user/:id` format.
396
+ * The plugin matches the path through `path-to-regexp`.
397
+ * @see https://github.com/pillarjs/path-to-regexp
398
+ */
399
+ url: '/api/test',
400
+ /**
401
+ * Value must be explicitly specified as `true`.
402
+ * The plugin needs to make a judgment based on this field.
403
+ */
404
+ ws: true,
405
+ /**
406
+ * Configure the WebSocketServer
407
+ * @see https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver
408
+ */
409
+ setup(wss) {
410
+ wss.on('connection', (ws, request) => {
411
+ ws.on('message', (rawData) => {})
412
+ ws.send('data')
413
+ })
414
+ }
415
+ })
384
416
  ```
385
417
 
386
418
  ### Request/Response Enhance
@@ -650,6 +682,78 @@ export default defineMock({
650
682
  })
651
683
  ```
652
684
 
685
+ **exp:** Graphql
686
+ ```ts
687
+ import { buildSchema, graphql } from 'graphql'
688
+ const schema = buildSchema(`
689
+ type Query {
690
+ hello: String
691
+ }
692
+ `)
693
+ const rootValue = { hello: () => 'Hello world!' }
694
+
695
+ export default defineMock({
696
+ url: '/api/graphql',
697
+ method: 'POST',
698
+ body: async (request) => {
699
+ const source = request.body.source
700
+ const { data } = await graphql({ schema, rootValue, source })
701
+ return data
702
+ },
703
+ })
704
+ ```
705
+
706
+ ```ts
707
+ fetch('/api/graphql', {
708
+ method: 'POST',
709
+ body: JSON.stringify({ source: '{ hello }' })
710
+ })
711
+ ```
712
+
713
+ **exp:** WebSocket Mock
714
+ ```ts
715
+ // ws.mock.ts
716
+ export default defineMock({
717
+ url: '/socket.io',
718
+ ws: true,
719
+ setup(wss) {
720
+ const wsMap = new Map()
721
+ wss.on('connection', (ws, req) => {
722
+ const token = req.getCookie('token')
723
+ wsMap.set(token, ws)
724
+ ws.on('message', (raw) => {
725
+ const data = JSON.parse(String(raw))
726
+ if (data.type === 'ping') return
727
+ // Broadcast
728
+ for (const [_token, _ws] of wsMap.entires()) {
729
+ if (_token !== token)
730
+ _ws.send(raw)
731
+ }
732
+ })
733
+ })
734
+ wss.on('error', (err) => {
735
+ console.error(err)
736
+ })
737
+ return () => {
738
+ wsMap.clear()
739
+ }
740
+ }
741
+ })
742
+ ```
743
+ ```ts
744
+ // app.ts
745
+ const ws = new WebSocket('ws://localhost:5173/socket.io')
746
+ ws.addEventListener('open', () => {
747
+ setInterval(() => {
748
+ // heartbeat
749
+ ws.send({ type: 'ping' })
750
+ }, 1000)
751
+ }, { once: true })
752
+ ws.addEventListener('message', (raw) => {
753
+ console.log(raw)
754
+ })
755
+ ```
756
+
653
757
  ## Mock Services
654
758
 
655
759
  In some scenarios, it may be necessary to use the data provided by mock services for display purposes, but the project may have already been packaged, built and deployed without support from `vite` and this plugin's mock service. Since this plugin supports importing various `node` modules in mock files at the design stage, the mock file cannot be inline into client build code.
package/README.zh-CN.md CHANGED
@@ -13,7 +13,7 @@
13
13
  <a href="https://www.npmjs.com/package/vite-plugin-mock-dev-server"><img alt="npm" src="https://img.shields.io/npm/v/vite-plugin-mock-dev-server?style=flat-square"></a>
14
14
  <img alt="node-current" src="https://img.shields.io/node/v/vite-plugin-mock-dev-server?style=flat-square">
15
15
  <img alt="npm peer dependency version" src="https://img.shields.io/npm/dependency-version/vite-plugin-mock-dev-server/peer/vite?style=flat-square">
16
- <img alt="npm" src="https://img.shields.io/npm/dm/vite-plugin-mock-dev-server?style=flat-square">
16
+ <img alt="npm" src="https://img.shields.io/npm/dt/vite-plugin-mock-dev-server?style=flat-square">
17
17
  <br>
18
18
  <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pengzhanbo/vite-plugin-mock-dev-server/lint.yml?style=flat-square">
19
19
  <a href="https://app.fossa.com/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server?ref=badge_shield"><img alt="fossa status" src="https://app.fossa.com/api/projects/git%2Bgithub.com%2Fpengzhanbo%2Fvite-plugin-mock-dev-server.svg?type=shield"></a>
@@ -37,13 +37,14 @@
37
37
  - 🎨 可选择你喜欢的任意用于生成mock数据库,如 `mockjs`,或者不使用其他库
38
38
  - 📥 路径规则匹配,请求参数匹配
39
39
  - ⚙️ 随意开启或关闭对某个接口的 mock配置
40
- - - 📀 支持多种响应体数据类型,包括 `text/json/buffer/stream`.
40
+ - 📀 支持多种响应体数据类型,包括 `text/json/buffer/stream`.
41
41
  - ⚖️ 使用 `server.proxy` 配置
42
42
  - 🍕 支持在 mock文件中使用 `viteConfig.define`配置字段
43
43
  - ⚓️ 支持在 mock文件中使用 `viteConfig.resolve.alias` 路径别名
44
44
  - 🌈 支持 `vite preview` 模式
45
45
  - 📤 支持 multipart 类型,模拟文件上传
46
46
  - 📥 支持模拟文件下载
47
+ - ⚜️ 支持模拟 `WebSocket`
47
48
  - 🗂 支持构建可独立部署的小型mock服务
48
49
 
49
50
 
@@ -140,12 +141,22 @@ export default defineConfig({
140
141
 
141
142
  **类型:** `string | string[]`
142
143
 
143
- 为mock服务器配置自定义匹配规则。任何请求路径以 `prefix` 值开头的请求将被代理到对应的目标。如果 `prefix` 值以 ^ 开头,将被识别为 RegExp。
144
+ 为mock服务器配置自定义匹配规则。任何请求路径以 `prefix` 值开头的请求将被代理到对应的目标。如果 `prefix` 值以 `^` 开头,将被识别为 RegExp。
144
145
 
145
146
  > 一般情况下, `server.proxy` 已经足够满足需求,添加此项是为了与某些场景兼容。
146
147
 
147
148
  **默认值:** `[]`
148
149
 
150
+ - `options.wsPrefix`
151
+
152
+ **类型:** `string | string[]`
153
+
154
+ 配置 webSocket 服务 匹配规则。任何请求路径以 `wsPrefix` 值开头的 `ws/wss` 协议请求,将被代理到对应的目标。
155
+ 如果`wsPrefix`值以 `^` 开头,将被识别为 RegExp。
156
+
157
+ > 与 http mock 默认使用 `viteConfig.server.proxy` 不同的是,`websocket mock` 不会使用 `viteConfig.server.proxy` 中的 ws 相关的配置,且配置在 `wsPrefix` 中的规则,不能同时配置在 `viteConfig.server.proxy`中,因为会导致在 vite 在启动服务时产生冲突,因为不能对同一个请求实现多个的 `WebSocketServer`实例。
158
+ > 该冲突既不是 `vite` 的问题,也不是插件的问题,这属于合理的错误类型。在进行 `WebSocket Mock`和 `WebSocket Proxy` 切换时,请注意配置不要出现重复导致冲突。
159
+
149
160
  - `option.include`
150
161
 
151
162
  **类型:** `string | string[]`
@@ -160,14 +171,7 @@ export default defineConfig({
160
171
 
161
172
  配置读取 mock文件时,需要排除的文件, 可以是一个 目录、glob、或者一个数组
162
173
 
163
- **默认值:**
164
- ```ts
165
- [
166
- '**/node_modules/**',
167
- '**/.vscode/**',
168
- '**/.git/**',
169
- ]
170
- ```
174
+ **默认值:** `['**/node_modules/**', '**/.vscode/**', '**/.git/**']`
171
175
 
172
176
  - `options.reload`
173
177
 
@@ -254,6 +258,7 @@ export default defineApiMock({
254
258
  ## Mock 配置
255
259
 
256
260
  ```ts
261
+ // 配置 http mock
257
262
  export default defineMock({
258
263
  /**
259
264
  * 请求地址,支持 `/api/user/:id` 格式
@@ -376,7 +381,32 @@ export default defineMock({
376
381
  res.end()
377
382
  }
378
383
  })
379
-
384
+ ```
385
+ ```ts
386
+ // 配置 WebSocket mock
387
+ export default defineMock({
388
+ /**
389
+ * 请求地址,支持 `/api/user/:id` 格式
390
+ * 插件通过 `path-to-regexp` 匹配路径
391
+ * @see https://github.com/pillarjs/path-to-regexp
392
+ */
393
+ url: '/api/test',
394
+ /**
395
+ * 必须显式的指定值为 `true`
396
+ * 插件内部需要根据此值进行判断
397
+ */
398
+ ws: true,
399
+ /**
400
+ * 配置 WebSocketServer
401
+ * @see https://github.com/websockets/ws/blob/master/doc/ws.md#class-websocketserver
402
+ */
403
+ setup(wss) {
404
+ wss.on('connection', (ws, request) => {
405
+ ws.on('message', (rawData) => {})
406
+ ws.send('data')
407
+ })
408
+ }
409
+ })
380
410
  ```
381
411
 
382
412
  ### Request/Response 增强
@@ -645,6 +675,78 @@ export default defineMock({
645
675
  })
646
676
  ```
647
677
 
678
+ **exp:** Graphql
679
+ ```ts
680
+ import { buildSchema, graphql } from 'graphql'
681
+ const schema = buildSchema(`
682
+ type Query {
683
+ hello: String
684
+ }
685
+ `)
686
+ const rootValue = { hello: () => 'Hello world!' }
687
+
688
+ export default defineMock({
689
+ url: '/api/graphql',
690
+ method: 'POST',
691
+ body: async (request) => {
692
+ const source = request.body.source
693
+ const { data } = await graphql({ schema, rootValue, source })
694
+ return data
695
+ },
696
+ })
697
+ ```
698
+
699
+ ```ts
700
+ fetch('/api/graphql', {
701
+ method: 'POST',
702
+ body: JSON.stringify({ source: '{ hello }' })
703
+ })
704
+ ```
705
+
706
+ **exp:** WebSocket Mock
707
+ ```ts
708
+ // ws.mock.ts
709
+ export default defineMock({
710
+ url: '/socket.io',
711
+ ws: true,
712
+ setup(wss) {
713
+ const wsMap = new Map()
714
+ wss.on('connection', (ws, req) => {
715
+ const token = req.getCookie('token')
716
+ wsMap.set(token, ws)
717
+ ws.on('message', (raw) => {
718
+ const data = JSON.parse(String(raw))
719
+ if (data.type === 'ping') return
720
+ // Broadcast
721
+ for (const [_token, _ws] of wsMap.entires()) {
722
+ if (_token !== token)
723
+ _ws.send(raw)
724
+ }
725
+ })
726
+ })
727
+ wss.on('error', (err) => {
728
+ console.error(err)
729
+ })
730
+ return () => {
731
+ wsMap.clear()
732
+ }
733
+ }
734
+ })
735
+ ```
736
+ ```ts
737
+ // app.ts
738
+ const ws = new WebSocket('ws://localhost:5173/socket.io')
739
+ ws.addEventListener('open', () => {
740
+ setInterval(() => {
741
+ // heartbeat
742
+ ws.send({ type: 'ping' })
743
+ }, 1000)
744
+ }, { once: true })
745
+ ws.addEventListener('message', (raw) => {
746
+ console.log(raw)
747
+ })
748
+ ```
749
+
648
750
  ## 独立部署的小型mock服务
649
751
 
650
752
  在一些场景中,可能会需要使用mock服务提供的数据支持,用于展示,但可能项目已完成打包构建部署,已脱离 `vite` 和本插件提供的 mock服务支持。由于本插件在设计之初,支持在mock文件中引入各种 `node` 模块,所以不能将 mock文件打包内联到客户端构建代码中。