vite-plugin-mock-dev-server 1.4.6 → 1.5.0
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 +45 -4
- package/README.zh-CN.md +43 -3
- package/dist/index.cjs +37 -18
- package/dist/index.d.cts +21 -6
- package/dist/index.d.ts +21 -6
- package/dist/index.js +36 -17
- package/package.json +17 -17
package/README.md
CHANGED
|
@@ -7,11 +7,12 @@
|
|
|
7
7
|
</p>
|
|
8
8
|
|
|
9
9
|
<br>
|
|
10
|
+
|
|
10
11
|
<p align="center">
|
|
11
12
|
<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
13
|
<img alt="node-current" src="https://img.shields.io/node/v/vite-plugin-mock-dev-server?style=flat-square">
|
|
13
14
|
<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/
|
|
15
|
+
<img alt="npm" src="https://img.shields.io/npm/dm/vite-plugin-mock-dev-server?style=flat-square">
|
|
15
16
|
<br>
|
|
16
17
|
<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
18
|
<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>
|
|
@@ -67,6 +68,7 @@ pnpm add -D vite-plugin-mock-dev-server
|
|
|
67
68
|
### Configuration
|
|
68
69
|
|
|
69
70
|
`vite.config.ts`
|
|
71
|
+
|
|
70
72
|
``` ts
|
|
71
73
|
import { defineConfig } from 'vite'
|
|
72
74
|
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
|
|
@@ -84,6 +86,7 @@ export default defineConfig({
|
|
|
84
86
|
}
|
|
85
87
|
})
|
|
86
88
|
```
|
|
89
|
+
|
|
87
90
|
The plugin will read the configuration of `server.proxy` or `options.prefix`, and enable mock matching for matched URLs.
|
|
88
91
|
|
|
89
92
|
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
|
|
|
97
100
|
By default, write mock data in the `mock` directory of your project's root directory:
|
|
98
101
|
|
|
99
102
|
`mock/**/*.mock.ts` :
|
|
103
|
+
|
|
100
104
|
``` ts
|
|
101
105
|
import { defineMock } from 'vite-plugin-mock-dev-server'
|
|
102
106
|
|
|
@@ -113,6 +117,7 @@ export default defineMock({
|
|
|
113
117
|
Vite plugin
|
|
114
118
|
|
|
115
119
|
`vite.config.ts`
|
|
120
|
+
|
|
116
121
|
``` ts
|
|
117
122
|
import { defineConfig } from 'vite'
|
|
118
123
|
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
|
|
@@ -192,6 +197,7 @@ export default defineConfig({
|
|
|
192
197
|
**Default:** `{}`
|
|
193
198
|
|
|
194
199
|
example: Configure to file upload dir
|
|
200
|
+
|
|
195
201
|
``` ts
|
|
196
202
|
MockDevServerPlugin({
|
|
197
203
|
formidableOptions: {
|
|
@@ -206,6 +212,12 @@ export default defineConfig({
|
|
|
206
212
|
|
|
207
213
|
**Default:** `{}`
|
|
208
214
|
|
|
215
|
+
- `options.bodyParserOptions`
|
|
216
|
+
|
|
217
|
+
Configure to `co-body`, see [co-body](https://github.com/cojs/co-body#options)
|
|
218
|
+
|
|
219
|
+
**Default:** `{}`
|
|
220
|
+
|
|
209
221
|
- `options.build`
|
|
210
222
|
|
|
211
223
|
The configuration needed to build a small, independently deployable mock service.
|
|
@@ -236,7 +248,7 @@ export default defineConfig({
|
|
|
236
248
|
|
|
237
249
|
- `options.priority`
|
|
238
250
|
|
|
239
|
-
Custom path matching rule priority。[read more](#
|
|
251
|
+
Custom path matching rule priority。[read more](#custom-path-matching-priority)
|
|
240
252
|
|
|
241
253
|
**Default:** `undefined`
|
|
242
254
|
|
|
@@ -399,6 +411,7 @@ export default defineMock({
|
|
|
399
411
|
},
|
|
400
412
|
})
|
|
401
413
|
```
|
|
414
|
+
|
|
402
415
|
``` ts
|
|
403
416
|
// Configure the WebSocket mock
|
|
404
417
|
export default defineMock({
|
|
@@ -486,8 +499,10 @@ type defineMockData<T> = (
|
|
|
486
499
|
) => [getter, setter] & { value: T }
|
|
487
500
|
```
|
|
488
501
|
|
|
489
|
-
|
|
502
|
+
### Exp
|
|
503
|
+
|
|
490
504
|
`data.ts`
|
|
505
|
+
|
|
491
506
|
```ts
|
|
492
507
|
import { defineMockData } from 'vite-plugin-mock-dev-server'
|
|
493
508
|
|
|
@@ -496,7 +511,9 @@ export default defineMockData('posts', [
|
|
|
496
511
|
{ id: '2', title: 'title2', content: 'content2' },
|
|
497
512
|
])
|
|
498
513
|
```
|
|
514
|
+
|
|
499
515
|
`*.mock.ts`
|
|
516
|
+
|
|
500
517
|
```ts
|
|
501
518
|
import { defineMock } from 'vite-plugin-mock-dev-server'
|
|
502
519
|
import posts from './data'
|
|
@@ -529,6 +546,7 @@ export default defineMock([
|
|
|
529
546
|
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.
|
|
530
547
|
|
|
531
548
|
Exp:
|
|
549
|
+
|
|
532
550
|
```ts
|
|
533
551
|
import { defineConfig } from 'vite'
|
|
534
552
|
import mockPlugin from 'vite-plugin-mock-dev-server'
|
|
@@ -576,6 +594,7 @@ export default defineConfig({
|
|
|
576
594
|
See more examples: [example](/example/)
|
|
577
595
|
|
|
578
596
|
**exp:** Match `/api/test`, And returns a response body content with empty data
|
|
597
|
+
|
|
579
598
|
``` ts
|
|
580
599
|
export default defineMock({
|
|
581
600
|
url: '/api/test',
|
|
@@ -583,6 +602,7 @@ export default defineMock({
|
|
|
583
602
|
```
|
|
584
603
|
|
|
585
604
|
**exp:** Match `/api/test` , And returns a static content data
|
|
605
|
+
|
|
586
606
|
``` ts
|
|
587
607
|
export default defineMock({
|
|
588
608
|
url: '/api/test',
|
|
@@ -591,6 +611,7 @@ export default defineMock({
|
|
|
591
611
|
```
|
|
592
612
|
|
|
593
613
|
**exp:** Only Support `GET` Method
|
|
614
|
+
|
|
594
615
|
``` ts
|
|
595
616
|
export default defineMock({
|
|
596
617
|
url: '/api/test',
|
|
@@ -599,6 +620,7 @@ export default defineMock({
|
|
|
599
620
|
```
|
|
600
621
|
|
|
601
622
|
**exp:** In the response header, add a custom header and cookie
|
|
623
|
+
|
|
602
624
|
``` ts
|
|
603
625
|
export default defineMock({
|
|
604
626
|
url: '/api/test',
|
|
@@ -606,6 +628,7 @@ export default defineMock({
|
|
|
606
628
|
cookies: { 'my-cookie': '123456789' },
|
|
607
629
|
})
|
|
608
630
|
```
|
|
631
|
+
|
|
609
632
|
``` ts
|
|
610
633
|
export default defineMock({
|
|
611
634
|
url: '/api/test',
|
|
@@ -619,6 +642,7 @@ export default defineMock({
|
|
|
619
642
|
```
|
|
620
643
|
|
|
621
644
|
**exp:** Define multiple mock requests for the same URL and match valid rules with validators
|
|
645
|
+
|
|
622
646
|
``` ts
|
|
623
647
|
export default defineMock([
|
|
624
648
|
// Match /api/test?a=1
|
|
@@ -653,6 +677,7 @@ export default defineMock([
|
|
|
653
677
|
```
|
|
654
678
|
|
|
655
679
|
**exp:** Response Delay
|
|
680
|
+
|
|
656
681
|
``` ts
|
|
657
682
|
export default defineMock({
|
|
658
683
|
url: '/api/test',
|
|
@@ -661,6 +686,7 @@ export default defineMock({
|
|
|
661
686
|
```
|
|
662
687
|
|
|
663
688
|
**exp:** The interface request failed
|
|
689
|
+
|
|
664
690
|
``` ts
|
|
665
691
|
export default defineMock({
|
|
666
692
|
url: '/api/test',
|
|
@@ -670,6 +696,7 @@ export default defineMock({
|
|
|
670
696
|
```
|
|
671
697
|
|
|
672
698
|
**exp:** Dynamic route matching
|
|
699
|
+
|
|
673
700
|
``` ts
|
|
674
701
|
export default defineMock({
|
|
675
702
|
url: '/api/user/:userId',
|
|
@@ -682,6 +709,7 @@ export default defineMock({
|
|
|
682
709
|
The `userId` in the route will be resolved into the `request.params` object.
|
|
683
710
|
|
|
684
711
|
**exp**:** Use the buffer to respond data
|
|
712
|
+
|
|
685
713
|
```ts
|
|
686
714
|
import { Buffer } from 'node:buffer'
|
|
687
715
|
|
|
@@ -693,6 +721,7 @@ export default defineMock({
|
|
|
693
721
|
body: Buffer.from(JSON.stringify({ a: 1 }))
|
|
694
722
|
})
|
|
695
723
|
```
|
|
724
|
+
|
|
696
725
|
``` ts
|
|
697
726
|
// When the type is buffer, the content-type is application/octet-stream.
|
|
698
727
|
// The data passed in through body will be converted to a buffer.
|
|
@@ -707,6 +736,7 @@ export default defineMock({
|
|
|
707
736
|
**exp:** Response file type
|
|
708
737
|
|
|
709
738
|
Simulate file download, and pass in the file reading stream.
|
|
739
|
+
|
|
710
740
|
``` ts
|
|
711
741
|
import { createReadStream } from 'node:fs'
|
|
712
742
|
|
|
@@ -717,11 +747,13 @@ export default defineMock({
|
|
|
717
747
|
body: () => createReadStream('./my-app.dmg')
|
|
718
748
|
})
|
|
719
749
|
```
|
|
750
|
+
|
|
720
751
|
```html
|
|
721
752
|
<a href="/api/download" download="my-app.dmg">Download File</a>
|
|
722
753
|
```
|
|
723
754
|
|
|
724
755
|
**exp:** Use `mockjs`:
|
|
756
|
+
|
|
725
757
|
``` ts
|
|
726
758
|
import Mock from 'mockjs'
|
|
727
759
|
|
|
@@ -734,9 +766,11 @@ export default defineMock({
|
|
|
734
766
|
})
|
|
735
767
|
})
|
|
736
768
|
```
|
|
769
|
+
|
|
737
770
|
You need install `mockjs`
|
|
738
771
|
|
|
739
772
|
**exp:** Use `response` to customize the response
|
|
773
|
+
|
|
740
774
|
``` ts
|
|
741
775
|
export default defineMock({
|
|
742
776
|
url: '/api/test',
|
|
@@ -756,6 +790,7 @@ export default defineMock({
|
|
|
756
790
|
```
|
|
757
791
|
|
|
758
792
|
**exp:** Use json / json5
|
|
793
|
+
|
|
759
794
|
``` json
|
|
760
795
|
{
|
|
761
796
|
"url": "/api/test",
|
|
@@ -768,6 +803,7 @@ export default defineMock({
|
|
|
768
803
|
**exp:** multipart, upload files.
|
|
769
804
|
|
|
770
805
|
use [`formidable`](https://www.npmjs.com/package/formidable#readme) to support.
|
|
806
|
+
|
|
771
807
|
``` html
|
|
772
808
|
<form action="/api/upload" method="post" enctype="multipart/form-data">
|
|
773
809
|
<p>
|
|
@@ -785,6 +821,7 @@ use [`formidable`](https://www.npmjs.com/package/formidable#readme) to support.
|
|
|
785
821
|
```
|
|
786
822
|
|
|
787
823
|
fields `files` mapping to `formidable.File`
|
|
824
|
+
|
|
788
825
|
``` ts
|
|
789
826
|
export default defineMock({
|
|
790
827
|
url: '/api/upload',
|
|
@@ -800,6 +837,7 @@ export default defineMock({
|
|
|
800
837
|
```
|
|
801
838
|
|
|
802
839
|
**exp:** Graphql
|
|
840
|
+
|
|
803
841
|
``` ts
|
|
804
842
|
import { buildSchema, graphql } from 'graphql'
|
|
805
843
|
|
|
@@ -829,6 +867,7 @@ fetch('/api/graphql', {
|
|
|
829
867
|
```
|
|
830
868
|
|
|
831
869
|
**exp:** WebSocket Mock
|
|
870
|
+
|
|
832
871
|
``` ts
|
|
833
872
|
// ws.mock.ts
|
|
834
873
|
export default defineMock({
|
|
@@ -857,6 +896,7 @@ export default defineMock({
|
|
|
857
896
|
}
|
|
858
897
|
})
|
|
859
898
|
```
|
|
899
|
+
|
|
860
900
|
``` ts
|
|
861
901
|
// app.ts
|
|
862
902
|
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
|
|
|
878
918
|
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.
|
|
879
919
|
|
|
880
920
|
The default output is built into the directory `dist/mockServer`, generating files as follows:
|
|
921
|
+
|
|
881
922
|
``` sh
|
|
882
923
|
./mockServer
|
|
883
924
|
├── index.js
|
|
@@ -898,7 +939,7 @@ You can access related `mock` interfaces through `localhost:8080/`.
|
|
|
898
939
|
## Contributors
|
|
899
940
|
|
|
900
941
|
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
|
|
901
|
-
[](#contributors
|
|
942
|
+
[](#contributors)
|
|
902
943
|
<!-- ALL-CONTRIBUTORS-BADGE:END -->
|
|
903
944
|
|
|
904
945
|
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
|
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/
|
|
16
|
+
<img alt="npm" src="https://img.shields.io/npm/dm/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>
|
|
@@ -69,6 +69,7 @@ pnpm add -D vite-plugin-mock-dev-server
|
|
|
69
69
|
### 配置
|
|
70
70
|
|
|
71
71
|
`vite.config.ts`
|
|
72
|
+
|
|
72
73
|
```ts
|
|
73
74
|
import { defineConfig } from 'vite'
|
|
74
75
|
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
|
|
@@ -86,6 +87,7 @@ export default defineConfig({
|
|
|
86
87
|
}
|
|
87
88
|
})
|
|
88
89
|
```
|
|
90
|
+
|
|
89
91
|
插件会读取 `server.proxy` 或 `options.prefix` 的配置,对匹配的 url 启用mock 匹配。
|
|
90
92
|
|
|
91
93
|
插件也会读取 `define` 配置, 支持在 mock 文件中直接使用。
|
|
@@ -98,6 +100,7 @@ export default defineConfig({
|
|
|
98
100
|
默认配置,在你的项目根目录的 `mock` 目录中编写mock数据:
|
|
99
101
|
|
|
100
102
|
`mock/**/*.mock.ts` :
|
|
103
|
+
|
|
101
104
|
```ts
|
|
102
105
|
import { defineMock } from 'vite-plugin-mock-dev-server'
|
|
103
106
|
|
|
@@ -114,6 +117,7 @@ export default defineMock({
|
|
|
114
117
|
vite plugin
|
|
115
118
|
|
|
116
119
|
`vite.config.ts`
|
|
120
|
+
|
|
117
121
|
```ts
|
|
118
122
|
import { defineConfig } from 'vite'
|
|
119
123
|
import mockDevServerPlugin from 'vite-plugin-mock-dev-server'
|
|
@@ -192,6 +196,7 @@ export default defineConfig({
|
|
|
192
196
|
**默认值:** `{}`
|
|
193
197
|
|
|
194
198
|
示例: 配置文件上传的存放目录
|
|
199
|
+
|
|
195
200
|
```ts
|
|
196
201
|
MockDevServerPlugin({
|
|
197
202
|
formidableOptions: {
|
|
@@ -199,12 +204,17 @@ export default defineConfig({
|
|
|
199
204
|
}
|
|
200
205
|
})
|
|
201
206
|
```
|
|
207
|
+
|
|
202
208
|
- `options.cookiesOptions`
|
|
203
209
|
|
|
204
210
|
配置 `cookies`, 查看 [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)
|
|
205
211
|
|
|
206
212
|
**默认值:** `{}`
|
|
207
213
|
|
|
214
|
+
- `options.bodyParserOptions`
|
|
215
|
+
|
|
216
|
+
配置 `co-body`, 查看 [co-body](https://github.com/cojs/co-body#options)
|
|
217
|
+
|
|
208
218
|
- `options.build`
|
|
209
219
|
|
|
210
220
|
需要构建可独立部署的小型mock服务时配置。
|
|
@@ -397,6 +407,7 @@ export default defineMock({
|
|
|
397
407
|
},
|
|
398
408
|
})
|
|
399
409
|
```
|
|
410
|
+
|
|
400
411
|
```ts
|
|
401
412
|
// 配置 WebSocket mock
|
|
402
413
|
export default defineMock({
|
|
@@ -481,8 +492,10 @@ type defineMockData<T> = (
|
|
|
481
492
|
) => [getter, setter] & { value: T }
|
|
482
493
|
```
|
|
483
494
|
|
|
484
|
-
|
|
495
|
+
### 用法
|
|
496
|
+
|
|
485
497
|
`data.ts`
|
|
498
|
+
|
|
486
499
|
```ts
|
|
487
500
|
import { defineMockData } from 'vite-plugin-mock-dev-server'
|
|
488
501
|
|
|
@@ -491,7 +504,9 @@ export default defineMockData('posts', [
|
|
|
491
504
|
{ id: '2', title: 'title2', content: 'content2' },
|
|
492
505
|
])
|
|
493
506
|
```
|
|
507
|
+
|
|
494
508
|
`*.mock.ts`
|
|
509
|
+
|
|
495
510
|
```ts
|
|
496
511
|
import { defineMock } from 'vite-plugin-mock-dev-server'
|
|
497
512
|
import posts from './data'
|
|
@@ -525,6 +540,7 @@ export default defineMock([
|
|
|
525
540
|
可以使用 `priority` 参数。
|
|
526
541
|
|
|
527
542
|
示例:
|
|
543
|
+
|
|
528
544
|
```ts
|
|
529
545
|
import { defineConfig } from 'vite'
|
|
530
546
|
import mockPlugin from 'vite-plugin-mock-dev-server'
|
|
@@ -557,7 +573,7 @@ export default defineConfig({
|
|
|
557
573
|
|
|
558
574
|
> **注意:**
|
|
559
575
|
>
|
|
560
|
-
>
|
|
576
|
+
> `priority` 虽然可以调整优先级,但大多数时候,你都没有必要这么做。
|
|
561
577
|
> 对于一些特殊情况的请求,可以使用 静态规则来替代 `priority`,静态规则总是拥有最高优先级。
|
|
562
578
|
|
|
563
579
|
## Example
|
|
@@ -567,6 +583,7 @@ export default defineConfig({
|
|
|
567
583
|
查看更多示例: [example](/example/)
|
|
568
584
|
|
|
569
585
|
**exp:** 命中 `/api/test` 请求,并返回一个 数据为空的响应体内容
|
|
586
|
+
|
|
570
587
|
```ts
|
|
571
588
|
export default defineMock({
|
|
572
589
|
url: '/api/test',
|
|
@@ -574,12 +591,14 @@ export default defineMock({
|
|
|
574
591
|
```
|
|
575
592
|
|
|
576
593
|
**exp:** 命中 `/api/test` 请求,并返回一个固定内容数据
|
|
594
|
+
|
|
577
595
|
```ts
|
|
578
596
|
export default defineMock({
|
|
579
597
|
url: '/api/test',
|
|
580
598
|
body: { a: 1 },
|
|
581
599
|
})
|
|
582
600
|
```
|
|
601
|
+
|
|
583
602
|
```ts
|
|
584
603
|
export default defineMock({
|
|
585
604
|
url: '/api/test',
|
|
@@ -588,6 +607,7 @@ export default defineMock({
|
|
|
588
607
|
```
|
|
589
608
|
|
|
590
609
|
**exp:** 限定只允许 `GET` 请求
|
|
610
|
+
|
|
591
611
|
```ts
|
|
592
612
|
export default defineMock({
|
|
593
613
|
url: '/api/test',
|
|
@@ -596,6 +616,7 @@ export default defineMock({
|
|
|
596
616
|
```
|
|
597
617
|
|
|
598
618
|
**exp:** 在返回的响应头中,添加自定义 header 和 cookie
|
|
619
|
+
|
|
599
620
|
```ts
|
|
600
621
|
export default defineMock({
|
|
601
622
|
url: '/api/test',
|
|
@@ -603,6 +624,7 @@ export default defineMock({
|
|
|
603
624
|
cookies: { 'my-cookie': '123456789' },
|
|
604
625
|
})
|
|
605
626
|
```
|
|
627
|
+
|
|
606
628
|
```ts
|
|
607
629
|
export default defineMock({
|
|
608
630
|
url: '/api/test',
|
|
@@ -616,6 +638,7 @@ export default defineMock({
|
|
|
616
638
|
```
|
|
617
639
|
|
|
618
640
|
**exp:** 定义多个相同url请求mock,并使用验证器匹配生效规则
|
|
641
|
+
|
|
619
642
|
```ts
|
|
620
643
|
export default defineMock([
|
|
621
644
|
// 命中 /api/test?a=1
|
|
@@ -649,6 +672,7 @@ export default defineMock([
|
|
|
649
672
|
```
|
|
650
673
|
|
|
651
674
|
**exp:** 延迟接口响应:
|
|
675
|
+
|
|
652
676
|
```ts
|
|
653
677
|
export default defineMock({
|
|
654
678
|
url: '/api/test',
|
|
@@ -657,6 +681,7 @@ export default defineMock({
|
|
|
657
681
|
```
|
|
658
682
|
|
|
659
683
|
**exp:** 使接口请求失败
|
|
684
|
+
|
|
660
685
|
```ts
|
|
661
686
|
export default defineMock({
|
|
662
687
|
url: '/api/test',
|
|
@@ -666,6 +691,7 @@ export default defineMock({
|
|
|
666
691
|
```
|
|
667
692
|
|
|
668
693
|
**exp:** 动态路由匹配
|
|
694
|
+
|
|
669
695
|
```ts
|
|
670
696
|
export default defineMock({
|
|
671
697
|
url: '/api/user/:userId',
|
|
@@ -678,6 +704,7 @@ export default defineMock({
|
|
|
678
704
|
路由中的 `userId`将会解析到 `request.params` 对象中.
|
|
679
705
|
|
|
680
706
|
**exp:** 使用 buffer 响应数据
|
|
707
|
+
|
|
681
708
|
```ts
|
|
682
709
|
import { Buffer } from 'node:buffer'
|
|
683
710
|
|
|
@@ -688,6 +715,7 @@ export default defineMock({
|
|
|
688
715
|
body: Buffer.from(JSON.stringify({ a: 1 }))
|
|
689
716
|
})
|
|
690
717
|
```
|
|
718
|
+
|
|
691
719
|
```ts
|
|
692
720
|
// 当 type 为 buffer 时,content-type 为 application/octet-stream,
|
|
693
721
|
// body 传入的数据会被转为 buffer
|
|
@@ -702,6 +730,7 @@ export default defineMock({
|
|
|
702
730
|
**exp:** 响应文件类型
|
|
703
731
|
|
|
704
732
|
模拟文件下载,传入文件读取流
|
|
733
|
+
|
|
705
734
|
```ts
|
|
706
735
|
import { createReadStream } from 'node:fs'
|
|
707
736
|
|
|
@@ -712,11 +741,13 @@ export default defineMock({
|
|
|
712
741
|
body: () => createReadStream('./my-app.dmg')
|
|
713
742
|
})
|
|
714
743
|
```
|
|
744
|
+
|
|
715
745
|
```html
|
|
716
746
|
<a href="/api/download" download="my-app.dmg">下载文件</a>
|
|
717
747
|
```
|
|
718
748
|
|
|
719
749
|
**exp:** 使用 `mockjs` 生成响应数据:
|
|
750
|
+
|
|
720
751
|
```ts
|
|
721
752
|
import Mock from 'mockjs'
|
|
722
753
|
|
|
@@ -729,9 +760,11 @@ export default defineMock({
|
|
|
729
760
|
})
|
|
730
761
|
})
|
|
731
762
|
```
|
|
763
|
+
|
|
732
764
|
请先安装 `mockjs`
|
|
733
765
|
|
|
734
766
|
**exp:** 使用 `response` 自定义响应
|
|
767
|
+
|
|
735
768
|
```ts
|
|
736
769
|
export default defineMock({
|
|
737
770
|
url: '/api/test',
|
|
@@ -751,6 +784,7 @@ export default defineMock({
|
|
|
751
784
|
```
|
|
752
785
|
|
|
753
786
|
**exp:** 使用 json / json5
|
|
787
|
+
|
|
754
788
|
```json
|
|
755
789
|
{
|
|
756
790
|
"url": "/api/test",
|
|
@@ -763,6 +797,7 @@ export default defineMock({
|
|
|
763
797
|
**exp:** multipart, 文件上传.
|
|
764
798
|
|
|
765
799
|
通过 [`formidable`](https://www.npmjs.com/package/formidable#readme) 支持。
|
|
800
|
+
|
|
766
801
|
``` html
|
|
767
802
|
<form action="/api/upload" method="post" enctype="multipart/form-data">
|
|
768
803
|
<p>
|
|
@@ -780,6 +815,7 @@ export default defineMock({
|
|
|
780
815
|
```
|
|
781
816
|
|
|
782
817
|
fields `files` 映射为 `formidable.File` 类型。
|
|
818
|
+
|
|
783
819
|
``` ts
|
|
784
820
|
export default defineMock({
|
|
785
821
|
url: '/api/upload',
|
|
@@ -795,6 +831,7 @@ export default defineMock({
|
|
|
795
831
|
```
|
|
796
832
|
|
|
797
833
|
**exp:** Graphql
|
|
834
|
+
|
|
798
835
|
```ts
|
|
799
836
|
import { buildSchema, graphql } from 'graphql'
|
|
800
837
|
|
|
@@ -824,6 +861,7 @@ fetch('/api/graphql', {
|
|
|
824
861
|
```
|
|
825
862
|
|
|
826
863
|
**exp:** WebSocket Mock
|
|
864
|
+
|
|
827
865
|
```ts
|
|
828
866
|
// ws.mock.ts
|
|
829
867
|
export default defineMock({
|
|
@@ -852,6 +890,7 @@ export default defineMock({
|
|
|
852
890
|
}
|
|
853
891
|
})
|
|
854
892
|
```
|
|
893
|
+
|
|
855
894
|
```ts
|
|
856
895
|
// app.ts
|
|
857
896
|
const ws = new WebSocket('ws://localhost:5173/socket.io')
|
|
@@ -873,6 +912,7 @@ ws.addEventListener('message', (raw) => {
|
|
|
873
912
|
为了能够满足这类场景,插件一方面提供了 `vite preview` 下的支持,同时还提供了在 `vite build` 时,也构建一个可独立部署的 小型mock服务应用,可以将这个应用部署到相关的环境,后通过其他http服务器如nginx做代理转发到实际端口实现mock支持。
|
|
874
913
|
|
|
875
914
|
构建默认输出到 `dist/mockServer` 目录中,并生成如下文件:
|
|
915
|
+
|
|
876
916
|
```sh
|
|
877
917
|
./mockServer
|
|
878
918
|
├── index.js
|
package/dist/index.cjs
CHANGED
|
@@ -44,7 +44,7 @@ __export(src_exports, {
|
|
|
44
44
|
});
|
|
45
45
|
module.exports = __toCommonJS(src_exports);
|
|
46
46
|
|
|
47
|
-
// node_modules/.pnpm/tsup@8.0.
|
|
47
|
+
// node_modules/.pnpm/tsup@8.0.2_typescript@5.4.3/node_modules/tsup/assets/cjs_shims.js
|
|
48
48
|
var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
|
|
49
49
|
var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
50
50
|
|
|
@@ -344,7 +344,7 @@ function canJsonParse(value) {
|
|
|
344
344
|
|
|
345
345
|
// src/build.ts
|
|
346
346
|
var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
|
|
347
|
-
var packageVersion = true ? "1.
|
|
347
|
+
var packageVersion = true ? "1.5.0" : "latest";
|
|
348
348
|
async function generateMockServer(ctx, config, options) {
|
|
349
349
|
const include = (0, import_utils2.toArray)(options.include);
|
|
350
350
|
const exclude = (0, import_utils2.toArray)(options.exclude);
|
|
@@ -380,6 +380,7 @@ async function generateMockServer(ctx, config, options) {
|
|
|
380
380
|
httpProxies,
|
|
381
381
|
wsProxies,
|
|
382
382
|
options.cookiesOptions,
|
|
383
|
+
options.bodyParserOptions,
|
|
383
384
|
options.priority,
|
|
384
385
|
options.build
|
|
385
386
|
)
|
|
@@ -451,7 +452,7 @@ function generatePackageJson(pkg, mockDeps) {
|
|
|
451
452
|
});
|
|
452
453
|
return JSON.stringify(mockPkg, null, 2);
|
|
453
454
|
}
|
|
454
|
-
function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, build2) {
|
|
455
|
+
function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, bodyParserOptions = {}, priority = {}, build2) {
|
|
455
456
|
const { serverPort, log } = build2;
|
|
456
457
|
return `import { createServer } from 'node:http';
|
|
457
458
|
import connect from 'connect';
|
|
@@ -465,6 +466,7 @@ const logger = createLogger('mock-server', '${log}');
|
|
|
465
466
|
const httpProxies = ${JSON.stringify(httpProxies)};
|
|
466
467
|
const wsProxies = ${JSON.stringify(wsProxies)};
|
|
467
468
|
const cookiesOptions = ${JSON.stringify(cookiesOptions)};
|
|
469
|
+
const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
|
|
468
470
|
const priority = ${JSON.stringify(priority)};
|
|
469
471
|
|
|
470
472
|
mockWebSocket({
|
|
@@ -481,6 +483,7 @@ app.use(baseMiddleware({ mockData }, {
|
|
|
481
483
|
proxies: httpProxies,
|
|
482
484
|
priority,
|
|
483
485
|
cookiesOptions,
|
|
486
|
+
bodyParserOptions,
|
|
484
487
|
logger,
|
|
485
488
|
}));
|
|
486
489
|
|
|
@@ -682,21 +685,34 @@ function twoPartMatch(rules) {
|
|
|
682
685
|
// src/parseReqBody.ts
|
|
683
686
|
var import_co_body = __toESM(require("co-body"), 1);
|
|
684
687
|
var import_formidable = __toESM(require("formidable"), 1);
|
|
685
|
-
async function parseReqBody(req,
|
|
688
|
+
async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
|
|
686
689
|
var _a;
|
|
687
690
|
const method = req.method.toUpperCase();
|
|
688
691
|
if (["GET", "DELETE", "HEAD"].includes(method))
|
|
689
692
|
return void 0;
|
|
690
693
|
const type = ((_a = req.headers["content-type"]) == null ? void 0 : _a.toLocaleLowerCase()) || "";
|
|
694
|
+
const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
|
|
691
695
|
try {
|
|
692
|
-
if (type.startsWith("application/json"))
|
|
693
|
-
return await import_co_body.default.json(req
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
696
|
+
if (type.startsWith("application/json")) {
|
|
697
|
+
return await import_co_body.default.json(req, {
|
|
698
|
+
limit: jsonLimit || limit,
|
|
699
|
+
...rest
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
if (type.startsWith("application/x-www-form-urlencoded")) {
|
|
703
|
+
return await import_co_body.default.form(req, {
|
|
704
|
+
limit: formLimit || limit,
|
|
705
|
+
...rest
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
if (type.startsWith("text/plain")) {
|
|
709
|
+
return await import_co_body.default.text(req, {
|
|
710
|
+
limit: textLimit || limit,
|
|
711
|
+
...rest
|
|
712
|
+
});
|
|
713
|
+
}
|
|
698
714
|
if (type.startsWith("multipart/form-data"))
|
|
699
|
-
return await parseMultipart(req,
|
|
715
|
+
return await parseMultipart(req, formidableOptions);
|
|
700
716
|
} catch (e) {
|
|
701
717
|
console.error(e);
|
|
702
718
|
}
|
|
@@ -793,6 +809,7 @@ function isIncluded(source, target) {
|
|
|
793
809
|
// src/baseMiddleware.ts
|
|
794
810
|
function baseMiddleware(mockLoader, {
|
|
795
811
|
formidableOptions = {},
|
|
812
|
+
bodyParserOptions = {},
|
|
796
813
|
proxies,
|
|
797
814
|
cookiesOptions,
|
|
798
815
|
logger,
|
|
@@ -809,7 +826,7 @@ function baseMiddleware(mockLoader, {
|
|
|
809
826
|
return next();
|
|
810
827
|
collectRequest(req);
|
|
811
828
|
const { query: refererQuery } = urlParse(req.headers.referer || "");
|
|
812
|
-
const reqBody = await parseReqBody(req, formidableOptions);
|
|
829
|
+
const reqBody = await parseReqBody(req, formidableOptions, bodyParserOptions);
|
|
813
830
|
const cookies = new import_cookies.default(req, res, cookiesOptions);
|
|
814
831
|
const getCookie = cookies.get.bind(cookies);
|
|
815
832
|
const method = req.method.toUpperCase();
|
|
@@ -1289,11 +1306,10 @@ var MockLoader = class extends import_node_events.default {
|
|
|
1289
1306
|
else
|
|
1290
1307
|
isESM = this.moduleType === "esm";
|
|
1291
1308
|
const { define, alias } = this.options;
|
|
1292
|
-
const { code, deps } = await transformWithEsbuild(
|
|
1293
|
-
|
|
1294
|
-
define,
|
|
1295
|
-
|
|
1296
|
-
});
|
|
1309
|
+
const { code, deps } = await transformWithEsbuild(
|
|
1310
|
+
filepath,
|
|
1311
|
+
{ isESM, define, alias }
|
|
1312
|
+
);
|
|
1297
1313
|
try {
|
|
1298
1314
|
const raw = await loadFromCode(
|
|
1299
1315
|
filepath,
|
|
@@ -1502,7 +1518,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
|
|
|
1502
1518
|
const { httpProxies } = ensureProxies(config.server.proxy || {});
|
|
1503
1519
|
const prefix = (0, import_utils14.toArray)(options.prefix);
|
|
1504
1520
|
const proxies = (0, import_utils14.uniq)([...prefix, ...httpProxies]);
|
|
1505
|
-
if (!proxies.length
|
|
1521
|
+
if (!proxies.length && !(0, import_utils14.toArray)(options.wsPrefix).length)
|
|
1506
1522
|
logger.warn(`No proxy was configured, mock server will not work. See ${import_picocolors5.default.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
|
|
1507
1523
|
mockWebSocket({
|
|
1508
1524
|
loader,
|
|
@@ -1529,6 +1545,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
|
|
|
1529
1545
|
formidableOptions: options.formidableOptions,
|
|
1530
1546
|
proxies,
|
|
1531
1547
|
cookiesOptions: options.cookiesOptions,
|
|
1548
|
+
bodyParserOptions: options.bodyParserOptions,
|
|
1532
1549
|
priority: options.priority,
|
|
1533
1550
|
logger
|
|
1534
1551
|
})
|
|
@@ -1578,6 +1595,7 @@ function mockDevServerPlugin({
|
|
|
1578
1595
|
formidableOptions = {},
|
|
1579
1596
|
build: build2 = false,
|
|
1580
1597
|
cookiesOptions = {},
|
|
1598
|
+
bodyParserOptions = {},
|
|
1581
1599
|
priority = {}
|
|
1582
1600
|
} = {}) {
|
|
1583
1601
|
const pluginOptions = {
|
|
@@ -1593,6 +1611,7 @@ function mockDevServerPlugin({
|
|
|
1593
1611
|
multiples: true,
|
|
1594
1612
|
...formidableOptions
|
|
1595
1613
|
},
|
|
1614
|
+
bodyParserOptions,
|
|
1596
1615
|
priority,
|
|
1597
1616
|
build: build2 ? Object.assign(
|
|
1598
1617
|
{
|
package/dist/index.d.cts
CHANGED
|
@@ -6,6 +6,7 @@ import Cookies from 'cookies';
|
|
|
6
6
|
import { CorsOptions } from 'cors';
|
|
7
7
|
import formidable from 'formidable';
|
|
8
8
|
import { WebSocketServer } from 'ws';
|
|
9
|
+
import { Options } from 'co-body';
|
|
9
10
|
import EventEmitter from 'node:events';
|
|
10
11
|
import chokidar from 'chokidar';
|
|
11
12
|
import { Http2SecureServer } from 'node:http2';
|
|
@@ -91,6 +92,14 @@ interface MockServerPluginOptions {
|
|
|
91
92
|
* @see [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)
|
|
92
93
|
*/
|
|
93
94
|
cookiesOptions?: Cookies.Option;
|
|
95
|
+
/**
|
|
96
|
+
* Configure to `co-body`
|
|
97
|
+
*
|
|
98
|
+
* 配置 `co-body`
|
|
99
|
+
*
|
|
100
|
+
* @see [co-body](https://github.com/cojs/co-body#options)
|
|
101
|
+
*/
|
|
102
|
+
bodyParserOptions?: BodyParserOptions;
|
|
94
103
|
/**
|
|
95
104
|
* When you need to build a small mock service, you can configure this option.
|
|
96
105
|
*
|
|
@@ -193,6 +202,11 @@ interface MockMatchSpecialPriority {
|
|
|
193
202
|
when: string[];
|
|
194
203
|
};
|
|
195
204
|
}
|
|
205
|
+
type BodyParserOptions = Options & {
|
|
206
|
+
jsonLimit?: string | number;
|
|
207
|
+
formLimit?: string | number;
|
|
208
|
+
textLimit?: string | number;
|
|
209
|
+
};
|
|
196
210
|
interface ServerBuildOption {
|
|
197
211
|
/**
|
|
198
212
|
* Service startup port
|
|
@@ -550,7 +564,7 @@ type LogType = 'info' | 'warn' | 'error' | 'debug';
|
|
|
550
564
|
type LogLevel = LogType | 'silent';
|
|
551
565
|
|
|
552
566
|
/** @deprecated The CJS build of vite-plugin-mock-dev-server's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details. */
|
|
553
|
-
declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, priority, }?: MockServerPluginOptions): Plugin[];
|
|
567
|
+
declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
|
|
554
568
|
|
|
555
569
|
/**
|
|
556
570
|
* mock config Type helper
|
|
@@ -627,10 +641,10 @@ type MockData<T = any> = readonly [
|
|
|
627
641
|
declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
|
|
628
642
|
|
|
629
643
|
interface Logger {
|
|
630
|
-
debug(msg: string, level?: boolean | LogLevel)
|
|
631
|
-
info(msg: string, level?: boolean | LogLevel)
|
|
632
|
-
warn(msg: string, level?: boolean | LogLevel)
|
|
633
|
-
error(msg: string, level?: boolean | LogLevel)
|
|
644
|
+
debug: (msg: string, level?: boolean | LogLevel) => void;
|
|
645
|
+
info: (msg: string, level?: boolean | LogLevel) => void;
|
|
646
|
+
warn: (msg: string, level?: boolean | LogLevel) => void;
|
|
647
|
+
error: (msg: string, level?: boolean | LogLevel) => void;
|
|
634
648
|
}
|
|
635
649
|
declare const logLevels: Record<LogLevel, number>;
|
|
636
650
|
declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
|
|
@@ -672,11 +686,12 @@ declare class MockLoader extends EventEmitter {
|
|
|
672
686
|
interface BaseMiddlewareOptions {
|
|
673
687
|
formidableOptions: MockServerPluginOptions['formidableOptions'];
|
|
674
688
|
cookiesOptions: MockServerPluginOptions['cookiesOptions'];
|
|
689
|
+
bodyParserOptions: MockServerPluginOptions['bodyParserOptions'];
|
|
675
690
|
proxies: string[];
|
|
676
691
|
logger: Logger;
|
|
677
692
|
priority: MockServerPluginOptions['priority'];
|
|
678
693
|
}
|
|
679
|
-
declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Connect.NextHandleFunction;
|
|
694
|
+
declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, bodyParserOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Connect.NextHandleFunction;
|
|
680
695
|
|
|
681
696
|
/**
|
|
682
697
|
* 不复用 `viteConfig.server.proxy` 中 websocket proxy的原因是,
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import Cookies from 'cookies';
|
|
|
6
6
|
import { CorsOptions } from 'cors';
|
|
7
7
|
import formidable from 'formidable';
|
|
8
8
|
import { WebSocketServer } from 'ws';
|
|
9
|
+
import { Options } from 'co-body';
|
|
9
10
|
import EventEmitter from 'node:events';
|
|
10
11
|
import chokidar from 'chokidar';
|
|
11
12
|
import { Http2SecureServer } from 'node:http2';
|
|
@@ -91,6 +92,14 @@ interface MockServerPluginOptions {
|
|
|
91
92
|
* @see [cookies](https://github.com/pillarjs/cookies#new-cookiesrequest-response--options)
|
|
92
93
|
*/
|
|
93
94
|
cookiesOptions?: Cookies.Option;
|
|
95
|
+
/**
|
|
96
|
+
* Configure to `co-body`
|
|
97
|
+
*
|
|
98
|
+
* 配置 `co-body`
|
|
99
|
+
*
|
|
100
|
+
* @see [co-body](https://github.com/cojs/co-body#options)
|
|
101
|
+
*/
|
|
102
|
+
bodyParserOptions?: BodyParserOptions;
|
|
94
103
|
/**
|
|
95
104
|
* When you need to build a small mock service, you can configure this option.
|
|
96
105
|
*
|
|
@@ -193,6 +202,11 @@ interface MockMatchSpecialPriority {
|
|
|
193
202
|
when: string[];
|
|
194
203
|
};
|
|
195
204
|
}
|
|
205
|
+
type BodyParserOptions = Options & {
|
|
206
|
+
jsonLimit?: string | number;
|
|
207
|
+
formLimit?: string | number;
|
|
208
|
+
textLimit?: string | number;
|
|
209
|
+
};
|
|
196
210
|
interface ServerBuildOption {
|
|
197
211
|
/**
|
|
198
212
|
* Service startup port
|
|
@@ -549,7 +563,7 @@ type FormidableFile = formidable.File | formidable.File[];
|
|
|
549
563
|
type LogType = 'info' | 'warn' | 'error' | 'debug';
|
|
550
564
|
type LogLevel = LogType | 'silent';
|
|
551
565
|
|
|
552
|
-
declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, priority, }?: MockServerPluginOptions): Plugin[];
|
|
566
|
+
declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
|
|
553
567
|
|
|
554
568
|
/**
|
|
555
569
|
* mock config Type helper
|
|
@@ -626,10 +640,10 @@ type MockData<T = any> = readonly [
|
|
|
626
640
|
declare function defineMockData<T = any>(key: string, initialData: T): MockData<T>;
|
|
627
641
|
|
|
628
642
|
interface Logger {
|
|
629
|
-
debug(msg: string, level?: boolean | LogLevel)
|
|
630
|
-
info(msg: string, level?: boolean | LogLevel)
|
|
631
|
-
warn(msg: string, level?: boolean | LogLevel)
|
|
632
|
-
error(msg: string, level?: boolean | LogLevel)
|
|
643
|
+
debug: (msg: string, level?: boolean | LogLevel) => void;
|
|
644
|
+
info: (msg: string, level?: boolean | LogLevel) => void;
|
|
645
|
+
warn: (msg: string, level?: boolean | LogLevel) => void;
|
|
646
|
+
error: (msg: string, level?: boolean | LogLevel) => void;
|
|
633
647
|
}
|
|
634
648
|
declare const logLevels: Record<LogLevel, number>;
|
|
635
649
|
declare function createLogger(prefix: string, defaultLevel?: LogLevel): Logger;
|
|
@@ -671,11 +685,12 @@ declare class MockLoader extends EventEmitter {
|
|
|
671
685
|
interface BaseMiddlewareOptions {
|
|
672
686
|
formidableOptions: MockServerPluginOptions['formidableOptions'];
|
|
673
687
|
cookiesOptions: MockServerPluginOptions['cookiesOptions'];
|
|
688
|
+
bodyParserOptions: MockServerPluginOptions['bodyParserOptions'];
|
|
674
689
|
proxies: string[];
|
|
675
690
|
logger: Logger;
|
|
676
691
|
priority: MockServerPluginOptions['priority'];
|
|
677
692
|
}
|
|
678
|
-
declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Connect.NextHandleFunction;
|
|
693
|
+
declare function baseMiddleware(mockLoader: MockLoader, { formidableOptions, bodyParserOptions, proxies, cookiesOptions, logger, priority, }: BaseMiddlewareOptions): Connect.NextHandleFunction;
|
|
679
694
|
|
|
680
695
|
/**
|
|
681
696
|
* 不复用 `viteConfig.server.proxy` 中 websocket proxy的原因是,
|
package/dist/index.js
CHANGED
|
@@ -294,7 +294,7 @@ function canJsonParse(value) {
|
|
|
294
294
|
|
|
295
295
|
// src/build.ts
|
|
296
296
|
var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
|
|
297
|
-
var packageVersion = true ? "1.
|
|
297
|
+
var packageVersion = true ? "1.5.0" : "latest";
|
|
298
298
|
async function generateMockServer(ctx, config, options) {
|
|
299
299
|
const include = toArray(options.include);
|
|
300
300
|
const exclude = toArray(options.exclude);
|
|
@@ -330,6 +330,7 @@ async function generateMockServer(ctx, config, options) {
|
|
|
330
330
|
httpProxies,
|
|
331
331
|
wsProxies,
|
|
332
332
|
options.cookiesOptions,
|
|
333
|
+
options.bodyParserOptions,
|
|
333
334
|
options.priority,
|
|
334
335
|
options.build
|
|
335
336
|
)
|
|
@@ -401,7 +402,7 @@ function generatePackageJson(pkg, mockDeps) {
|
|
|
401
402
|
});
|
|
402
403
|
return JSON.stringify(mockPkg, null, 2);
|
|
403
404
|
}
|
|
404
|
-
function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, priority = {}, build2) {
|
|
405
|
+
function generatorServerEntryCode(httpProxies, wsProxies, cookiesOptions = {}, bodyParserOptions = {}, priority = {}, build2) {
|
|
405
406
|
const { serverPort, log } = build2;
|
|
406
407
|
return `import { createServer } from 'node:http';
|
|
407
408
|
import connect from 'connect';
|
|
@@ -415,6 +416,7 @@ const logger = createLogger('mock-server', '${log}');
|
|
|
415
416
|
const httpProxies = ${JSON.stringify(httpProxies)};
|
|
416
417
|
const wsProxies = ${JSON.stringify(wsProxies)};
|
|
417
418
|
const cookiesOptions = ${JSON.stringify(cookiesOptions)};
|
|
419
|
+
const bodyParserOptions = ${JSON.stringify(bodyParserOptions)};
|
|
418
420
|
const priority = ${JSON.stringify(priority)};
|
|
419
421
|
|
|
420
422
|
mockWebSocket({
|
|
@@ -431,6 +433,7 @@ app.use(baseMiddleware({ mockData }, {
|
|
|
431
433
|
proxies: httpProxies,
|
|
432
434
|
priority,
|
|
433
435
|
cookiesOptions,
|
|
436
|
+
bodyParserOptions,
|
|
434
437
|
logger,
|
|
435
438
|
}));
|
|
436
439
|
|
|
@@ -645,21 +648,34 @@ function twoPartMatch(rules) {
|
|
|
645
648
|
// src/parseReqBody.ts
|
|
646
649
|
import bodyParser from "co-body";
|
|
647
650
|
import formidable from "formidable";
|
|
648
|
-
async function parseReqBody(req,
|
|
651
|
+
async function parseReqBody(req, formidableOptions, bodyParserOptions = {}) {
|
|
649
652
|
var _a;
|
|
650
653
|
const method = req.method.toUpperCase();
|
|
651
654
|
if (["GET", "DELETE", "HEAD"].includes(method))
|
|
652
655
|
return void 0;
|
|
653
656
|
const type = ((_a = req.headers["content-type"]) == null ? void 0 : _a.toLocaleLowerCase()) || "";
|
|
657
|
+
const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
|
|
654
658
|
try {
|
|
655
|
-
if (type.startsWith("application/json"))
|
|
656
|
-
return await bodyParser.json(req
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
659
|
+
if (type.startsWith("application/json")) {
|
|
660
|
+
return await bodyParser.json(req, {
|
|
661
|
+
limit: jsonLimit || limit,
|
|
662
|
+
...rest
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
if (type.startsWith("application/x-www-form-urlencoded")) {
|
|
666
|
+
return await bodyParser.form(req, {
|
|
667
|
+
limit: formLimit || limit,
|
|
668
|
+
...rest
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
if (type.startsWith("text/plain")) {
|
|
672
|
+
return await bodyParser.text(req, {
|
|
673
|
+
limit: textLimit || limit,
|
|
674
|
+
...rest
|
|
675
|
+
});
|
|
676
|
+
}
|
|
661
677
|
if (type.startsWith("multipart/form-data"))
|
|
662
|
-
return await parseMultipart(req,
|
|
678
|
+
return await parseMultipart(req, formidableOptions);
|
|
663
679
|
} catch (e) {
|
|
664
680
|
console.error(e);
|
|
665
681
|
}
|
|
@@ -756,6 +772,7 @@ function isIncluded(source, target) {
|
|
|
756
772
|
// src/baseMiddleware.ts
|
|
757
773
|
function baseMiddleware(mockLoader, {
|
|
758
774
|
formidableOptions = {},
|
|
775
|
+
bodyParserOptions = {},
|
|
759
776
|
proxies,
|
|
760
777
|
cookiesOptions,
|
|
761
778
|
logger,
|
|
@@ -772,7 +789,7 @@ function baseMiddleware(mockLoader, {
|
|
|
772
789
|
return next();
|
|
773
790
|
collectRequest(req);
|
|
774
791
|
const { query: refererQuery } = urlParse(req.headers.referer || "");
|
|
775
|
-
const reqBody = await parseReqBody(req, formidableOptions);
|
|
792
|
+
const reqBody = await parseReqBody(req, formidableOptions, bodyParserOptions);
|
|
776
793
|
const cookies = new Cookies(req, res, cookiesOptions);
|
|
777
794
|
const getCookie = cookies.get.bind(cookies);
|
|
778
795
|
const method = req.method.toUpperCase();
|
|
@@ -1258,11 +1275,10 @@ var MockLoader = class extends EventEmitter {
|
|
|
1258
1275
|
else
|
|
1259
1276
|
isESM = this.moduleType === "esm";
|
|
1260
1277
|
const { define, alias } = this.options;
|
|
1261
|
-
const { code, deps } = await transformWithEsbuild(
|
|
1262
|
-
|
|
1263
|
-
define,
|
|
1264
|
-
|
|
1265
|
-
});
|
|
1278
|
+
const { code, deps } = await transformWithEsbuild(
|
|
1279
|
+
filepath,
|
|
1280
|
+
{ isESM, define, alias }
|
|
1281
|
+
);
|
|
1266
1282
|
try {
|
|
1267
1283
|
const raw = await loadFromCode(
|
|
1268
1284
|
filepath,
|
|
@@ -1471,7 +1487,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
|
|
|
1471
1487
|
const { httpProxies } = ensureProxies(config.server.proxy || {});
|
|
1472
1488
|
const prefix = toArray3(options.prefix);
|
|
1473
1489
|
const proxies = uniq2([...prefix, ...httpProxies]);
|
|
1474
|
-
if (!proxies.length
|
|
1490
|
+
if (!proxies.length && !toArray3(options.wsPrefix).length)
|
|
1475
1491
|
logger.warn(`No proxy was configured, mock server will not work. See ${c2.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
|
|
1476
1492
|
mockWebSocket({
|
|
1477
1493
|
loader,
|
|
@@ -1498,6 +1514,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
|
|
|
1498
1514
|
formidableOptions: options.formidableOptions,
|
|
1499
1515
|
proxies,
|
|
1500
1516
|
cookiesOptions: options.cookiesOptions,
|
|
1517
|
+
bodyParserOptions: options.bodyParserOptions,
|
|
1501
1518
|
priority: options.priority,
|
|
1502
1519
|
logger
|
|
1503
1520
|
})
|
|
@@ -1547,6 +1564,7 @@ function mockDevServerPlugin({
|
|
|
1547
1564
|
formidableOptions = {},
|
|
1548
1565
|
build: build2 = false,
|
|
1549
1566
|
cookiesOptions = {},
|
|
1567
|
+
bodyParserOptions = {},
|
|
1550
1568
|
priority = {}
|
|
1551
1569
|
} = {}) {
|
|
1552
1570
|
const pluginOptions = {
|
|
@@ -1562,6 +1580,7 @@ function mockDevServerPlugin({
|
|
|
1562
1580
|
multiples: true,
|
|
1563
1581
|
...formidableOptions
|
|
1564
1582
|
},
|
|
1583
|
+
bodyParserOptions,
|
|
1565
1584
|
priority,
|
|
1566
1585
|
build: build2 ? Object.assign(
|
|
1567
1586
|
{
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-mock-dev-server",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
5
|
-
"packageManager": "pnpm@8.
|
|
4
|
+
"version": "1.5.0",
|
|
5
|
+
"packageManager": "pnpm@8.15.5",
|
|
6
6
|
"author": "pengzhanbo <q942450674@outlook.com> (https://github.com/pengzhanbo)",
|
|
7
7
|
"license": "MIT",
|
|
8
8
|
"homepage": "https://vite-plugin-mock-dev-server.netlify.app",
|
|
@@ -37,23 +37,23 @@
|
|
|
37
37
|
"dist"
|
|
38
38
|
],
|
|
39
39
|
"engines": {
|
|
40
|
-
"node": "^
|
|
40
|
+
"node": "^18 || >= 20"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
43
|
"vite": ">=3.0.0"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@pengzhanbo/utils": "^1.1.
|
|
46
|
+
"@pengzhanbo/utils": "^1.1.2",
|
|
47
47
|
"@rollup/pluginutils": "^5.1.0",
|
|
48
|
-
"chokidar": "^3.
|
|
48
|
+
"chokidar": "^3.6.0",
|
|
49
49
|
"co-body": "^6.1.0",
|
|
50
50
|
"cookies": "^0.9.1",
|
|
51
51
|
"cors": "^2.8.5",
|
|
52
52
|
"debug": "^4.3.4",
|
|
53
|
-
"esbuild": "^0.
|
|
53
|
+
"esbuild": "^0.20.2",
|
|
54
54
|
"fast-glob": "^3.3.2",
|
|
55
55
|
"formidable": "2.1.2",
|
|
56
|
-
"http-status": "^1.7.
|
|
56
|
+
"http-status": "^1.7.4",
|
|
57
57
|
"is-core-module": "^2.13.1",
|
|
58
58
|
"json5": "^2.2.3",
|
|
59
59
|
"mime-types": "^2.1.35",
|
|
@@ -62,25 +62,25 @@
|
|
|
62
62
|
"ws": "^8.16.0"
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
|
-
"@pengzhanbo/eslint-config": "^1.
|
|
65
|
+
"@pengzhanbo/eslint-config": "^1.7.0",
|
|
66
66
|
"@types/co-body": "^6.1.3",
|
|
67
|
-
"@types/cookies": "^0.
|
|
67
|
+
"@types/cookies": "^0.9.0",
|
|
68
68
|
"@types/cors": "^2.8.17",
|
|
69
69
|
"@types/debug": "^4.1.12",
|
|
70
70
|
"@types/formidable": "2.0.6",
|
|
71
71
|
"@types/is-core-module": "^2.2.2",
|
|
72
72
|
"@types/mime-types": "^2.1.4",
|
|
73
|
-
"@types/node": "^20.11.
|
|
73
|
+
"@types/node": "^20.11.30",
|
|
74
74
|
"@types/ws": "^8.5.10",
|
|
75
|
-
"bumpp": "^9.
|
|
75
|
+
"bumpp": "^9.4.0",
|
|
76
76
|
"conventional-changelog-cli": "^4.1.0",
|
|
77
|
-
"eslint": "^8.
|
|
77
|
+
"eslint": "^8.57.0",
|
|
78
78
|
"mockjs": "^1.1.0",
|
|
79
|
-
"tsup": "^8.0.
|
|
80
|
-
"typescript": "^5.
|
|
81
|
-
"vite": "^5.
|
|
82
|
-
"vitepress": "^1.0.
|
|
83
|
-
"vitest": "^1.
|
|
79
|
+
"tsup": "^8.0.2",
|
|
80
|
+
"typescript": "^5.4.3",
|
|
81
|
+
"vite": "^5.2.6",
|
|
82
|
+
"vitepress": "^1.0.1",
|
|
83
|
+
"vitest": "^1.4.0"
|
|
84
84
|
},
|
|
85
85
|
"scripts": {
|
|
86
86
|
"build": "tsup && node ./deprecate.mjs",
|