1
0
mirror of https://github.com/fumiama/paper-manager.git synced 2026-06-13 13:16:55 +08:00

optimize vben/mock

This commit is contained in:
源文雨
2023-03-11 18:07:45 +08:00
parent a42e2f450b
commit 47e9935c88
9 changed files with 155 additions and 155 deletions

View File

@@ -1,18 +1,18 @@
import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'; import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
const modules = import.meta.globEager('./**/*.ts'); const modules = import.meta.globEager('./**/*.ts')
const mockModules: any[] = []; const mockModules: any[] = []
Object.keys(modules).forEach((key) => { Object.keys(modules).forEach((key) => {
if (key.includes('/_')) { if (key.includes('/_')) {
return; return
} }
mockModules.push(...modules[key].default); mockModules.push(...modules[key].default)
}); })
/** /**
* Used in a production environment. Need to manually import all modules * Used in a production environment. Need to manually import all modules
*/ */
export function setupProdMockServer() { export function setupProdMockServer() {
createProdMockServer(mockModules); createProdMockServer(mockModules)
} }

View File

@@ -1,5 +1,5 @@
// Interface data format used to return a unified format // Interface data format used to return a unified format
import { ResultEnum } from '/@/enums/httpEnum'; import { ResultEnum } from '/@/enums/httpEnum'
export function resultSuccess<T = Recordable>(result: T, { message = 'ok' } = {}) { export function resultSuccess<T = Recordable>(result: T, { message = 'ok' } = {}) {
return { return {
@@ -7,7 +7,7 @@ export function resultSuccess<T = Recordable>(result: T, { message = 'ok' } = {}
result, result,
message, message,
type: 'success', type: 'success',
}; }
} }
export function resultPageSuccess<T = any>( export function resultPageSuccess<T = any>(
@@ -16,7 +16,7 @@ export function resultPageSuccess<T = any>(
list: T[], list: T[],
{ message = 'ok' } = {}, { message = 'ok' } = {},
) { ) {
const pageData = pagination(page, pageSize, list); const pageData = pagination(page, pageSize, list)
return { return {
...resultSuccess({ ...resultSuccess({
@@ -24,7 +24,7 @@ export function resultPageSuccess<T = any>(
total: list.length, total: list.length,
}), }),
message, message,
}; }
} }
export function resultError( export function resultError(
@@ -36,21 +36,21 @@ export function resultError(
result, result,
message, message,
type: 'error', type: 'error',
}; }
} }
export function pagination<T = any>(pageNo: number, pageSize: number, array: T[]): T[] { export function pagination<T = any>(pageNo: number, pageSize: number, array: T[]): T[] {
const offset = (pageNo - 1) * Number(pageSize); const offset = (pageNo - 1) * Number(pageSize)
return offset + Number(pageSize) >= array.length return offset + Number(pageSize) >= array.length
? array.slice(offset, array.length) ? array.slice(offset, array.length)
: array.slice(offset, offset + Number(pageSize)); : array.slice(offset, offset + Number(pageSize))
} }
export interface requestParams { export interface requestParams {
method: string; method: string
body: any; body: any
headers?: { authorization?: string }; headers?: { authorization?: string }
query: any; query: any
} }
/** /**
@@ -58,5 +58,5 @@ export interface requestParams {
* *
*/ */
export function getRequestToken({ headers }: requestParams): string | undefined { export function getRequestToken({ headers }: requestParams): string | undefined {
return headers?.authorization; return headers?.authorization
} }

View File

@@ -1,15 +1,15 @@
import { MockMethod } from 'vite-plugin-mock'; import { MockMethod } from 'vite-plugin-mock'
import { resultSuccess, resultError } from '../_util'; import { resultSuccess, resultError } from '../_util'
import { ResultEnum } from '../../src/enums/httpEnum'; import { ResultEnum } from '../../src/enums/httpEnum'
const userInfo = { const userInfo = {
name: 'Vben', name: 'fumiama',
userid: '00000001', userid: '00000001',
email: 'test@gmail.com', email: 'fumiama@demo.com',
signature: '海纳百川,有容乃大', signature: '天何所沓,十二焉分。日月安属,列星安陈。',
introduction: '微笑着,努力着,欣赏着', introduction: '日は山の端にかかりぬ。',
title: '交互专家', title: '超级管理员',
group: '某某某事业群某某平台部某某技术部UED', group: '信息与通信工程学院-网络工程系',
tags: [ tags: [
{ {
key: '0', key: '0',
@@ -38,10 +38,10 @@ const userInfo = {
], ],
notifyCount: 12, notifyCount: 12,
unreadCount: 11, unreadCount: 11,
country: 'China', country: '中国',
address: 'Xiamen City 77', address: '四川成都',
phone: '0592-268888888', phone: '028-61830156',
}; }
export default [ export default [
{ {
@@ -49,7 +49,7 @@ export default [
timeout: 1000, timeout: 1000,
method: 'get', method: 'get',
response: () => { response: () => {
return resultSuccess(userInfo); return resultSuccess(userInfo)
}, },
}, },
{ {
@@ -57,7 +57,7 @@ export default [
method: 'post', method: 'post',
statusCode: 401, statusCode: 401,
response: () => { response: () => {
return resultError(); return resultError()
}, },
}, },
{ {
@@ -65,7 +65,7 @@ export default [
method: 'post', method: 'post',
statusCode: 200, statusCode: 200,
response: () => { response: () => {
return resultError('Token Expired!', { code: ResultEnum.TIMEOUT as number }); return resultError('Token Expired!', { code: ResultEnum.TIMEOUT as number })
}, },
}, },
] as MockMethod[]; ] as MockMethod[]

View File

@@ -1,5 +1,5 @@
import { MockMethod } from 'vite-plugin-mock'; import { MockMethod } from 'vite-plugin-mock'
import { resultSuccess } from '../_util'; import { resultSuccess } from '../_util'
const areaList: any[] = [ const areaList: any[] = [
{ {
@@ -308,18 +308,18 @@ const areaList: any[] = [
customized: false, customized: false,
usable: true, usable: true,
}, },
]; ]
export default [ export default [
{ {
url: '/basic-api/cascader/getAreaRecord', url: '/basic-api/cascader/getAreaRecord',
timeout: 1000, timeout: 1000,
method: 'post', method: 'post',
response: ({ body }) => { response: ({ body }) => {
const { parentCode } = body || {}; const { parentCode } = body || {}
if (!parentCode) { if (!parentCode) {
return resultSuccess(areaList.filter((it) => it.code === '430000')); return resultSuccess(areaList.filter((it) => it.code === '430000'))
} }
return resultSuccess(areaList.filter((it) => it.parentCode === parentCode)); return resultSuccess(areaList.filter((it) => it.parentCode === parentCode))
}, },
}, },
] as MockMethod[]; ] as MockMethod[]

View File

@@ -1,18 +1,18 @@
import { MockMethod } from 'vite-plugin-mock'; import { MockMethod } from 'vite-plugin-mock'
import { resultSuccess } from '../_util'; import { resultSuccess } from '../_util'
const demoList = (keyword, count = 20) => { const demoList = (keyword: string, count = 20) => {
const result = { const result = {
list: [] as any[], list: [] as any[],
}; }
for (let index = 0; index < count; index++) { for (let index = 0; index < count; index++) {
result.list.push({ result.list.push({
name: `${keyword ?? ''}选项${index}`, name: `${keyword ?? ''}选项${index}`,
id: `${index}`, id: `${index}`,
}); })
} }
return result; return result
}; }
export default [ export default [
{ {
@@ -20,9 +20,9 @@ export default [
timeout: 1000, timeout: 1000,
method: 'get', method: 'get',
response: ({ query }) => { response: ({ query }) => {
const { keyword, count } = query; const { keyword, count } = query
console.log(keyword); console.log(keyword)
return resultSuccess(demoList(keyword, count)); return resultSuccess(demoList(keyword, count))
}, },
}, },
] as MockMethod[]; ] as MockMethod[]

View File

@@ -1,8 +1,8 @@
import { MockMethod } from 'vite-plugin-mock'; import { MockMethod } from 'vite-plugin-mock'
import { resultError, resultPageSuccess, resultSuccess } from '../_util'; import { resultError, resultPageSuccess, resultSuccess } from '../_util'
const accountList = (() => { const accountList = (() => {
const result: any[] = []; const result: any[] = []
for (let index = 0; index < 20; index++) { for (let index = 0; index < 20; index++) {
result.push({ result.push({
id: `${index}`, id: `${index}`,
@@ -13,61 +13,61 @@ const accountList = (() => {
createTime: '@datetime', createTime: '@datetime',
remark: '@cword(10,20)', remark: '@cword(10,20)',
'status|1': ['0', '1'], 'status|1': ['0', '1'],
}); })
} }
return result; return result
})(); })()
const roleList = (() => { const roleList = (() => {
const result: any[] = []; const result: any[] = []
for (let index = 0; index < 4; index++) { for (let index = 0; index < 4; index++) {
result.push({ result.push({
id: index + 1, id: index + 1,
orderNo: `${index + 1}`, orderNo: `${index + 1}`,
roleName: ['超级管理员', '管理员', '文章管理员', '普通用户'][index], roleName: ['超级管理员', '权限管理员', '归档管理员', '普通用户'][index],
roleValue: '@first', roleValue: '@first',
createTime: '@datetime', createTime: '@datetime',
remark: '@cword(10,20)', remark: '@cword(10,20)',
menu: [['0', '1', '2'], ['0', '1'], ['0', '2'], ['2']][index], menu: [['0', '1', '2'], ['0', '1'], ['0', '2'], ['2']][index],
'status|1': ['0', '1'], 'status|1': ['0', '1'],
}); })
} }
return result; return result
})(); })()
const deptList = (() => { const deptList = (() => {
const result: any[] = []; const result: any[] = []
for (let index = 0; index < 3; index++) { for (let index = 0; index < 3; index++) {
result.push({ result.push({
id: `${index}`, id: `${index}`,
deptName: ['华东分部', '华南分部', '西北分部'][index], deptName: ['清水河校区', '沙河校区', '九里堤校区'][index],
orderNo: index + 1, orderNo: index + 1,
createTime: '@datetime', createTime: '@datetime',
remark: '@cword(10,20)', remark: '@cword(10,20)',
'status|1': ['0', '0', '1'], 'status|1': ['0', '0', '1'],
children: (() => { children: (() => {
const children: any[] = []; const children: any[] = []
for (let j = 0; j < 4; j++) { for (let j = 0; j < 4; j++) {
children.push({ children.push({
id: `${index}-${j}`, id: `${index}-${j}`,
deptName: ['研发部', '市场部', '商务部', '财务部'][j], deptName: ['TCP/IP课程组', '接入网课程组', '信号与系统课程组', '大学物理课程组'][j],
orderNo: j + 1, orderNo: j + 1,
createTime: '@datetime', createTime: '@datetime',
remark: '@cword(10,20)', remark: '@cword(10,20)',
'status|1': ['0', '1'], 'status|1': ['0', '1'],
parentDept: `${index}`, parentDept: `${index}`,
children: undefined, children: undefined,
}); })
} }
return children; return children
})(), })(),
}); })
} }
return result; return result
})(); })()
const menuList = (() => { const menuList = (() => {
const result: any[] = []; const result: any[] = []
for (let index = 0; index < 3; index++) { for (let index = 0; index < 3; index++) {
result.push({ result.push({
id: `${index}`, id: `${index}`,
@@ -80,7 +80,7 @@ const menuList = (() => {
createTime: '@datetime', createTime: '@datetime',
'status|1': ['0', '0', '1'], 'status|1': ['0', '0', '1'],
children: (() => { children: (() => {
const children: any[] = []; const children: any[] = []
for (let j = 0; j < 4; j++) { for (let j = 0; j < 4; j++) {
children.push({ children.push({
id: `${index}-${j}`, id: `${index}-${j}`,
@@ -99,7 +99,7 @@ const menuList = (() => {
'status|1': ['0', '1'], 'status|1': ['0', '1'],
parentMenu: `${index}`, parentMenu: `${index}`,
children: (() => { children: (() => {
const children: any[] = []; const children: any[] = []
for (let k = 0; k < 4; k++) { for (let k = 0; k < 4; k++) {
children.push({ children.push({
id: `${index}-${j}-${k}`, id: `${index}-${j}-${k}`,
@@ -121,18 +121,18 @@ const menuList = (() => {
'status|1': ['0', '1'], 'status|1': ['0', '1'],
parentMenu: `${index}-${j}`, parentMenu: `${index}-${j}`,
children: undefined, children: undefined,
}); })
} }
return children; return children
})(), })(),
}); })
} }
return children; return children
})(), })(),
}); })
} }
return result; return result
})(); })()
export default [ export default [
{ {
@@ -140,8 +140,8 @@ export default [
timeout: 100, timeout: 100,
method: 'get', method: 'get',
response: ({ query }) => { response: ({ query }) => {
const { page = 1, pageSize = 20 } = query; const { page = 1, pageSize = 20 } = query
return resultPageSuccess(page, pageSize, accountList); return resultPageSuccess(page, pageSize, accountList)
}, },
}, },
{ {
@@ -149,8 +149,8 @@ export default [
timeout: 100, timeout: 100,
method: 'get', method: 'get',
response: ({ query }) => { response: ({ query }) => {
const { page = 1, pageSize = 20 } = query; const { page = 1, pageSize = 20 } = query
return resultPageSuccess(page, pageSize, roleList); return resultPageSuccess(page, pageSize, roleList)
}, },
}, },
{ {
@@ -158,8 +158,8 @@ export default [
timeout: 500, timeout: 500,
method: 'post', method: 'post',
response: ({ query }) => { response: ({ query }) => {
const { id, status } = query; const { id, status } = query
return resultSuccess({ id, status }); return resultSuccess({ id, status })
}, },
}, },
{ {
@@ -167,7 +167,7 @@ export default [
timeout: 100, timeout: 100,
method: 'get', method: 'get',
response: () => { response: () => {
return resultSuccess(roleList); return resultSuccess(roleList)
}, },
}, },
{ {
@@ -175,7 +175,7 @@ export default [
timeout: 100, timeout: 100,
method: 'get', method: 'get',
response: () => { response: () => {
return resultSuccess(deptList); return resultSuccess(deptList)
}, },
}, },
{ {
@@ -183,7 +183,7 @@ export default [
timeout: 100, timeout: 100,
method: 'get', method: 'get',
response: () => { response: () => {
return resultSuccess(menuList); return resultSuccess(menuList)
}, },
}, },
{ {
@@ -191,12 +191,12 @@ export default [
timeout: 500, timeout: 500,
method: 'post', method: 'post',
response: ({ body }) => { response: ({ body }) => {
const { account } = body || {}; const { account } = body || {}
if (account && account.indexOf('admin') !== -1) { if (account && account.indexOf('admin') !== -1) {
return resultError('该字段不能包含admin'); return resultError('该字段不能包含admin')
} else { } else {
return resultSuccess(`${account} can use`); return resultSuccess(`${account} can use`)
} }
}, },
}, },
] as MockMethod[]; ] as MockMethod[]

View File

@@ -1,17 +1,17 @@
import { MockMethod } from 'vite-plugin-mock'; import { MockMethod } from 'vite-plugin-mock'
import { Random } from 'mockjs'; import { Random } from 'mockjs'
import { resultPageSuccess } from '../_util'; import { resultPageSuccess } from '../_util'
function getRandomPics(count = 10): string[] { function getRandomPics(count = 10): string[] {
const arr: string[] = []; const arr: string[] = []
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
arr.push(Random.image('800x600', Random.color(), Random.color(), Random.title())); arr.push(Random.image('800x600', Random.color(), Random.color(), Random.title()))
} }
return arr; return arr
} }
const demoList = (() => { const demoList = (() => {
const result: any[] = []; const result: any[] = []
for (let index = 0; index < 200; index++) { for (let index = 0; index < 200; index++) {
result.push({ result.push({
id: `${index}`, id: `${index}`,
@@ -34,10 +34,10 @@ const demoList = (() => {
time: `@time('HH:mm')`, time: `@time('HH:mm')`,
'no|100000-10000000': 100000, 'no|100000-10000000': 100000,
'status|1': ['normal', 'enable', 'disable'], 'status|1': ['normal', 'enable', 'disable'],
}); })
} }
return result; return result
})(); })()
export default [ export default [
{ {
@@ -45,8 +45,8 @@ export default [
timeout: 100, timeout: 100,
method: 'get', method: 'get',
response: ({ query }) => { response: ({ query }) => {
const { page = 1, pageSize = 20 } = query; const { page = 1, pageSize = 20 } = query
return resultPageSuccess(page, pageSize, demoList); return resultPageSuccess(page, pageSize, demoList)
}, },
}, },
] as MockMethod[]; ] as MockMethod[]

View File

@@ -1,28 +1,28 @@
import { MockMethod } from 'vite-plugin-mock'; import { MockMethod } from 'vite-plugin-mock'
import { resultSuccess } from '../_util'; import { resultSuccess } from '../_util'
const demoTreeList = (keyword) => { const demoTreeList = (keyword: string) => {
const result = { const result = {
list: [] as Recordable[], list: [] as Recordable[],
}; }
for (let index = 0; index < 5; index++) { for (let index = 0; index < 5; index++) {
const children: Recordable[] = []; const children: Recordable[] = []
for (let j = 0; j < 3; j++) { for (let j = 0; j < 3; j++) {
children.push({ children.push({
title: `${keyword ?? ''}选项${index}-${j}`, title: `${keyword ?? ''}选项${index}-${j}`,
value: `${index}-${j}`, value: `${index}-${j}`,
key: `${index}-${j}`, key: `${index}-${j}`,
}); })
} }
result.list.push({ result.list.push({
title: `${keyword ?? ''}选项${index}`, title: `${keyword ?? ''}选项${index}`,
value: `${index}`, value: `${index}`,
key: `${index}`, key: `${index}`,
children, children,
}); })
} }
return result; return result
}; }
export default [ export default [
{ {
@@ -30,9 +30,9 @@ export default [
timeout: 1000, timeout: 1000,
method: 'get', method: 'get',
response: ({ query }) => { response: ({ query }) => {
const { keyword } = query; const { keyword } = query
console.log(keyword); console.log(keyword)
return resultSuccess(demoTreeList(keyword)); return resultSuccess(demoTreeList(keyword))
}, },
}, },
] as MockMethod[]; ] as MockMethod[]

View File

@@ -1,20 +1,20 @@
import { MockMethod } from 'vite-plugin-mock'; import { MockMethod } from 'vite-plugin-mock'
import { resultError, resultSuccess, getRequestToken, requestParams } from '../_util'; import { resultError, resultSuccess, getRequestToken, requestParams } from '../_util'
export function createFakeUserList() { export function createFakeUserList() {
return [ return [
{ {
userId: '1', userId: '00000001',
username: 'vben', username: 'fumiama',
realName: 'Vben Admin', realName: '源文雨',
avatar: 'https://q1.qlogo.cn/g?b=qq&nk=190848757&s=640', avatar: 'https://q1.qlogo.cn/g?b=qq&nk=1332524221&s=640',
desc: 'manager', desc: 'manager',
password: '123456', password: '123456',
token: 'fakeToken1', token: 'fakeToken1',
homePath: '/dashboard/analysis', homePath: '/dashboard/analysis',
roles: [ roles: [
{ {
roleName: 'Super Admin', roleName: '超级管理员',
value: 'super', value: 'super',
}, },
], ],
@@ -35,14 +35,14 @@ export function createFakeUserList() {
}, },
], ],
}, },
]; ]
} }
const fakeCodeList: any = { const fakeCodeList: any = {
'1': ['1000', '3000', '5000'], '1': ['1000', '3000', '5000'],
'2': ['2000', '4000', '6000'], '2': ['2000', '4000', '6000'],
}; }
export default [ export default [
// mock user login // mock user login
{ {
@@ -50,14 +50,14 @@ export default [
timeout: 200, timeout: 200,
method: 'post', method: 'post',
response: ({ body }) => { response: ({ body }) => {
const { username, password } = body; const { username, password } = body
const checkUser = createFakeUserList().find( const checkUser = createFakeUserList().find(
(item) => item.username === username && password === item.password, (item) => item.username === username && password === item.password,
); )
if (!checkUser) { if (!checkUser) {
return resultError('Incorrect account or password'); return resultError('Incorrect account or password')
} }
const { userId, username: _username, token, realName, desc, roles } = checkUser; const { userId, username: _username, token, realName, desc, roles } = checkUser
return resultSuccess({ return resultSuccess({
roles, roles,
userId, userId,
@@ -65,20 +65,20 @@ export default [
token, token,
realName, realName,
desc, desc,
}); })
}, },
}, },
{ {
url: '/basic-api/getUserInfo', url: '/basic-api/getUserInfo',
method: 'get', method: 'get',
response: (request: requestParams) => { response: (request: requestParams) => {
const token = getRequestToken(request); const token = getRequestToken(request)
if (!token) return resultError('Invalid token'); if (!token) return resultError('Invalid token')
const checkUser = createFakeUserList().find((item) => item.token === token); const checkUser = createFakeUserList().find((item) => item.token === token)
if (!checkUser) { if (!checkUser) {
return resultError('The corresponding user information was not obtained!'); return resultError('The corresponding user information was not obtained!')
} }
return resultSuccess(checkUser); return resultSuccess(checkUser)
}, },
}, },
{ {
@@ -86,15 +86,15 @@ export default [
timeout: 200, timeout: 200,
method: 'get', method: 'get',
response: (request: requestParams) => { response: (request: requestParams) => {
const token = getRequestToken(request); const token = getRequestToken(request)
if (!token) return resultError('Invalid token'); if (!token) return resultError('Invalid token')
const checkUser = createFakeUserList().find((item) => item.token === token); const checkUser = createFakeUserList().find((item) => item.token === token)
if (!checkUser) { if (!checkUser) {
return resultError('Invalid token!'); return resultError('Invalid token!')
} }
const codeList = fakeCodeList[checkUser.userId]; const codeList = fakeCodeList[checkUser.userId]
return resultSuccess(codeList); return resultSuccess(codeList)
}, },
}, },
{ {
@@ -102,13 +102,13 @@ export default [
timeout: 200, timeout: 200,
method: 'get', method: 'get',
response: (request: requestParams) => { response: (request: requestParams) => {
const token = getRequestToken(request); const token = getRequestToken(request)
if (!token) return resultError('Invalid token'); if (!token) return resultError('Invalid token')
const checkUser = createFakeUserList().find((item) => item.token === token); const checkUser = createFakeUserList().find((item) => item.token === token)
if (!checkUser) { if (!checkUser) {
return resultError('Invalid token!'); return resultError('Invalid token!')
} }
return resultSuccess(undefined, { message: 'Token has been destroyed' }); return resultSuccess(undefined, { message: 'Token has been destroyed' })
}, },
}, },
{ {
@@ -116,7 +116,7 @@ export default [
statusCode: 405, statusCode: 405,
method: 'get', method: 'get',
response: () => { response: () => {
return resultError('Error!'); return resultError('Error!')
}, },
}, },
] as MockMethod[]; ] as MockMethod[]