Commit acd525b winches
committed
1 parent 65dc4ad commit acd525b Copy full SHA for acd525b
File tree 4 files changed +58
-1
lines changed
4 files changed +58
-1
lines changed Original file line number Diff line number Diff line change
1
+ import { interceptMock } from './intercept'
2
+ import { getOptions } from './utils'
3
+ import { resolve } from 'path'
4
+ import { scanDirFile } from '@winches/utils'
5
+
6
+ async function main ( ) {
7
+ const { mockPath = '__mock__' } = await getOptions ( )
8
+ const mockDir = resolve ( process . cwd ( ) , mockPath )
9
+ const mockList = scanDirFile ( mockDir )
10
+ . map ( path => path . slice ( path . indexOf ( mockDir ) + mockDir . length ) )
11
+ . map ( path => path . replace ( / \. .* / g, '' ) )
12
+
13
+ // 拦截请求
14
+ await interceptMock ( mockList , mockDir )
15
+
16
+ console . log ( ) ;
17
+ console . log ( 'Success:成功拦截请求 ' + mockList ) ;
18
+ }
19
+
20
+ main ( )
Original file line number Diff line number Diff line change
1
+ import Mock from 'mockjs'
2
+ import { join } from 'path'
3
+
4
+ export async function interceptMock ( mockList , mockDir ) {
5
+ for ( const item of mockList ) {
6
+ newItem = item . replace ( / \\ / g, '\/' )
7
+ // 判断是否为动态路径
8
+ if ( newItem . includes ( ':' ) ) {
9
+ const path = newItem . replace ( ':' , '/:' )
10
+ await addRoutes ( path , item )
11
+ continue
12
+ }
13
+ await addRoutes ( newItem , item )
14
+ }
15
+
16
+ async function addRoutes ( url , name ) {
17
+ const path = join ( mockDir , `${ name } .js` )
18
+ const mockFn = await import ( path )
19
+ Mock . mock ( url , 'GET' , mockFn )
20
+ Mock . mock ( url , 'POST' , mockFn )
21
+ }
22
+ }
Original file line number Diff line number Diff line change
1
+ import { existsSync } from 'fs'
2
+ import { resolve } from 'path'
3
+
4
+ export async function getOptions ( ) {
5
+ async function getOpts ( path ) {
6
+ const absPath = resolve ( process . cwd ( ) , path )
7
+ if ( ! existsSync ( absPath ) )
8
+ return null
9
+ return await import ( absPath )
10
+ }
11
+ const opts = getOpts ( 'mock.config.js' ) || getOpts ( 'mock.config.cjs' )
12
+ || getOpts ( 'package.json' ) || { }
13
+
14
+ return opts
15
+ }
Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ function getOptions() {
10
10
return require ( absPath )
11
11
}
12
12
const opts = getOpts ( 'mock.config.js' ) || getOpts ( 'mock.config.cjs' )
13
- || getOpts ( 'package.json' ) || undefined
13
+ || getOpts ( 'package.json' ) || { }
14
14
const { mockPath, watch, port } = opts
15
15
16
16
return {
You can’t perform that action at this time.
0 commit comments