Skip to content

Commit acd525b

Browse files
author
winches
committed
feat: 新增拦截请求
1 parent 65dc4ad commit acd525b

File tree

4 files changed

+58
-1
lines changed

4 files changed

+58
-1
lines changed

intercept/index.js

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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()

intercept/intercept.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}

intercept/utils.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
}

src/utils/index.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ function getOptions() {
1010
return require(absPath)
1111
}
1212
const opts = getOpts('mock.config.js') || getOpts('mock.config.cjs')
13-
|| getOpts('package.json') || undefined
13+
|| getOpts('package.json') || {}
1414
const { mockPath, watch, port } = opts
1515

1616
return {

0 commit comments

Comments
 (0)