Optimize mock related files and variable names.

This commit is contained in:
zuiidea
2018-09-17 20:54:06 +08:00
parent abfcf2460e
commit 5aa187334a
13 changed files with 203 additions and 122 deletions
+40
View File
@@ -0,0 +1,40 @@
/**
* Query objects that specify keys and values in an array where all values are objects.
* @param {array} array An array where all values are objects, like [{key:1},{key:2}].
* @param {string} key The key of the object that needs to be queried.
* @param {string} value The value of the object that needs to be queried.
* @return {object|null} Return frist object when query success.
*/
export function queryArray(array, key, value) {
if (!Array.isArray(array)) {
return null
}
const item = array.filter(_ => _[key] === value)
if (item.length) {
return item[0]
}
return null
}
export const Constant = {
ApiPrefix: '/api/v1',
NotFound: {
message: 'Not Found',
documentation_url: '',
},
Color: {
green: '#64ea91',
blue: '#8fc9fb',
purple: '#d897eb',
red: '#f69899',
yellow: '#f8c82e',
peach: '#f797d6',
borderBase: '#e5e5e5',
borderSplit: '#f4f4f4',
grass: '#d6fbb5',
sky: '#c1e0fc',
},
}
export Mock from 'mockjs'
export qs from 'qs'
+27 -21
View File
@@ -1,21 +1,22 @@
const Mock = require('mockjs')
const config = require('../src/utils/config')
const config = {
apiPrefix: '/api/v1',
}
const queryArray = (array, key, keyAlias = 'key') => {
if (!(array instanceof Array)) {
/**
* Query objects that specify keys and values in an array where all values are objects.
* @param {array} array An array where all values are objects, like [{key:1},{key:2}].
* @param {string} key The key of the object that needs to be queried.
* @param {string} value The value of the object that needs to be queried.
* @return {object|null} Return frist object when query success.
*/
export function queryArray(array, key, value) {
if (!Array.isArray(array)) {
return null
}
let data
for (const item of array) {
if (item[keyAlias] === key) {
data = item
break
}
}
if (data) {
return data
const item = array.filter(_ => _[key] === value)
if (item.length) {
return item[0]
}
return null
}
@@ -25,12 +26,11 @@ const NOTFOUND = {
documentation_url: 'http://localhost:8000/request',
}
let postId = 0
const posts = Mock.mock({
'data|100': [
{
id () {
id() {
postId += 1
return postId + 10000
},
@@ -42,13 +42,19 @@ const posts = Mock.mock({
'views|10-200': 1,
'comments|10-200': 1,
visibility: () => {
return Mock.mock('@pick(["Public",'
+ '"Password protected", '
+ '"Private"])')
return Mock.mock(
'@pick(["Public",' + '"Password protected", ' + '"Private"])'
)
},
date: '@dateTime',
image () {
return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.author.substr(0, 1))
image() {
return Mock.Random.image(
'100x100',
Mock.Random.color(),
'#757575',
'png',
this.author.substr(0, 1)
)
},
},
],
+3 -6
View File
@@ -1,9 +1,6 @@
import { Color } from '../src/utils/theme'
import { Mock, Constant } from './_utils'
const Mock = require('mockjs')
const config = require('../src/utils/config')
const { apiPrefix } = config
const { ApiPrefix, Color } = Constant
const Dashboard = Mock.mock({
'sales|8': [
@@ -139,7 +136,7 @@ const Dashboard = Mock.mock({
})
module.exports = {
[`GET ${apiPrefix}/dashboard`](req, res) {
[`GET ${ApiPrefix}/dashboard`](req, res) {
res.json(Dashboard)
},
}
+21 -21
View File
@@ -1,7 +1,7 @@
const { config } = require('./common')
import { Constant } from './_utils'
const { ApiPrefix } = Constant
const { apiPrefix } = config
let database = [
const database = [
{
id: '1',
icon: 'dashboard',
@@ -10,80 +10,80 @@ let database = [
},
{
id: '2',
bpid: '1',
breadcrumbParentId: '1',
name: 'Users',
icon: 'user',
route: '/user',
},
{
id: '7',
bpid: '1',
breadcrumbParentId: '1',
name: 'Posts',
icon: 'shopping-cart',
route: '/post',
},
{
id: '21',
mpid: '-1',
bpid: '2',
menuParentId: '-1',
breadcrumbParentId: '2',
name: 'User Detail',
route: '/user/:id',
},
{
id: '3',
bpid: '1',
breadcrumbParentId: '1',
name: 'Request',
icon: 'api',
route: '/request',
},
{
id: '4',
bpid: '1',
breadcrumbParentId: '1',
name: 'UI Element',
icon: 'camera-o',
},
{
id: '43',
bpid: '4',
mpid: '4',
breadcrumbParentId: '4',
menuParentId: '4',
name: 'DropOption',
icon: 'bars',
route: '/UIElement/dropOption',
},
{
id: '45',
bpid: '4',
mpid: '4',
breadcrumbParentId: '4',
menuParentId: '4',
name: 'Editor',
icon: 'edit',
route: '/UIElement/editor',
},
{
id: '5',
bpid: '1',
breadcrumbParentId: '1',
name: 'Charts',
icon: 'code-o',
},
{
id: '51',
bpid: '5',
mpid: '5',
breadcrumbParentId: '5',
menuParentId: '5',
name: 'ECharts',
icon: 'line-chart',
route: '/chart/ECharts',
},
{
id: '52',
bpid: '5',
mpid: '5',
breadcrumbParentId: '5',
menuParentId: '5',
name: 'highCharts',
icon: 'bar-chart',
route: '/chart/highCharts',
},
{
id: '53',
bpid: '5',
mpid: '5',
breadcrumbParentId: '5',
menuParentId: '5',
name: 'Rechartst',
icon: 'area-chart',
route: '/chart/Recharts',
@@ -91,7 +91,7 @@ let database = [
]
module.exports = {
[`GET ${apiPrefix}/menus`](req, res) {
[`GET ${ApiPrefix}/menus`](req, res) {
res.status(200).json(database)
},
}
+43 -7
View File
@@ -1,11 +1,43 @@
const { config, posts } = require('./common')
import { Mock, Constant } from './_utils'
const { apiPrefix } = config
let database = posts
const { ApiPrefix } = Constant
let postId = 0
const database = Mock.mock({
'data|100': [
{
id() {
postId += 1
return postId + 10000
},
'status|1-2': 1,
title: '@title',
author: '@last',
categories: '@word',
tags: '@word',
'views|10-200': 1,
'comments|10-200': 1,
visibility: () => {
return Mock.mock(
'@pick(["Public",' + '"Password protected", ' + '"Private"])'
)
},
date: '@dateTime',
image() {
return Mock.Random.image(
'100x100',
Mock.Random.color(),
'#757575',
'png',
this.author.substr(0, 1)
)
},
},
],
}).data
module.exports = {
[`GET ${apiPrefix}/posts`] (req, res) {
[`GET ${ApiPrefix}/posts`](req, res) {
const { query } = req
let { pageSize, page, ...other } = query
pageSize = pageSize || 10
@@ -14,9 +46,13 @@ module.exports = {
let newData = database
for (let key in other) {
if ({}.hasOwnProperty.call(other, key)) {
newData = newData.filter((item) => {
newData = newData.filter(item => {
if ({}.hasOwnProperty.call(item, key)) {
return String(item[key]).trim().indexOf(decodeURI(other[key]).trim()) > -1
return (
String(item[key])
.trim()
.indexOf(decodeURI(other[key]).trim()) > -1
)
}
return true
})
+11 -13
View File
@@ -1,8 +1,6 @@
const qs = require('qs')
const Mock = require('mockjs')
const config = require('../src/utils/config')
import { Mock, Constant, qs } from './_utils'
const { apiPrefix } = config
const { ApiPrefix } = Constant
let usersListData = Mock.mock({
'data|80-100': [
@@ -90,7 +88,7 @@ const NOTFOUND = {
module.exports = {
[`POST ${apiPrefix}/user/login`] (req, res) {
[`POST ${ApiPrefix}/user/login`] (req, res) {
const { username, password } = req.body
const user = adminUsers.filter(item => item.username === username)
@@ -107,12 +105,12 @@ module.exports = {
}
},
[`GET ${apiPrefix}/user/logout`] (req, res) {
[`GET ${ApiPrefix}/user/logout`] (req, res) {
res.clearCookie('token')
res.status(200).end()
},
[`GET ${apiPrefix}/user`] (req, res) {
[`GET ${ApiPrefix}/user`] (req, res) {
const cookie = req.headers.cookie || ''
const cookies = qs.parse(cookie.replace(/\s/g, ''), { delimiter: ';' })
const response = {}
@@ -137,7 +135,7 @@ module.exports = {
res.json(response)
},
[`GET ${apiPrefix}/users`] (req, res) {
[`GET ${ApiPrefix}/users`] (req, res) {
const { query } = req
let { pageSize, page, ...other } = query
pageSize = pageSize || 10
@@ -173,14 +171,14 @@ module.exports = {
})
},
[`POST ${apiPrefix}/users/delete`] (req, res) {
[`POST ${ApiPrefix}/users/delete`] (req, res) {
const { ids } = req.body
database = database.filter(item => !ids.some(_ => _ === item.id))
res.status(204).end()
},
[`POST ${apiPrefix}/user`] (req, res) {
[`POST ${ApiPrefix}/user`] (req, res) {
const newData = req.body
newData.createTime = Mock.mock('@now')
newData.avatar = newData.avatar || Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', newData.nickName.substr(0, 1))
@@ -191,7 +189,7 @@ module.exports = {
res.status(200).end()
},
[`GET ${apiPrefix}/user/:id`] (req, res) {
[`GET ${ApiPrefix}/user/:id`] (req, res) {
const { id } = req.params
const data = queryArray(database, id, 'id')
if (data) {
@@ -201,7 +199,7 @@ module.exports = {
}
},
[`DELETE ${apiPrefix}/user/:id`] (req, res) {
[`DELETE ${ApiPrefix}/user/:id`] (req, res) {
const { id } = req.params
const data = queryArray(database, id, 'id')
if (data) {
@@ -212,7 +210,7 @@ module.exports = {
}
},
[`PATCH ${apiPrefix}/user/:id`] (req, res) {
[`PATCH ${ApiPrefix}/user/:id`] (req, res) {
const { id } = req.params
const editItem = req.body
let isExist = false
+8 -8
View File
@@ -10,31 +10,31 @@ import styles from './Layout.less'
@withI18n()
class Bread extends PureComponent {
render() {
const { menu, location, i18n } = this.props
const { menuList, location, i18n } = this.props
// 匹配当前路由
let pathArray = []
let current
for (let index in menu) {
for (let index in menuList) {
if (
menu[index].route &&
pathMatchRegexp(menu[index].route, location.pathname)
menuList[index].route &&
pathMatchRegexp(menuList[index].route, location.pathname)
) {
current = menu[index]
current = menuList[index]
break
}
}
const getPathArray = item => {
pathArray.unshift(item)
if (item.bpid) {
getPathArray(queryArray(menu, 'id', item.bpid))
if (item.breadcrumbParentId) {
getPathArray(queryArray(menuList, 'id', item.breadcrumbParentId))
}
}
let paramMap = {}
if (!current) {
pathArray.push(
menu[0] || {
menuList[0] || {
id: 1,
icon: 'laptop',
name: i18n.t`Dashboard`,
+3 -3
View File
@@ -18,11 +18,11 @@ const Header = ({
switchMenuPopover,
navOpenKeys,
changeOpenKeys,
menu,
menuList,
}) => {
let handleClickMenu = e => e.key === 'logout' && logout()
const menusProps = {
menu,
menuList,
siderFold: false,
darkTheme: false,
isNavbar,
@@ -81,7 +81,7 @@ const Header = ({
}
Header.propTypes = {
menu: PropTypes.array,
menuList: PropTypes.array,
user: PropTypes.object,
logout: PropTypes.func,
switchSider: PropTypes.func,
+16 -11
View File
@@ -14,14 +14,14 @@ class Menus extends PureComponent {
darkTheme,
navOpenKeys,
changeOpenKeys,
menu,
menuList,
location,
} = this.props
// 生成树状
const menuTree = arrayToTree(
menu.filter(_ => _.mpid !== '-1'),
menuList.filter(_ => _.menuParentId !== '-1'),
'id',
'mpid'
'menuParentId'
)
const levelMap = {}
@@ -29,8 +29,8 @@ class Menus extends PureComponent {
const getMenus = (menuTreeN, siderFoldN) => {
return menuTreeN.map(item => {
if (item.children) {
if (item.mpid) {
levelMap[item.id] = item.mpid
if (item.menuParentId) {
levelMap[item.id] = item.menuParentId
}
return (
<SubMenu
@@ -106,10 +106,10 @@ class Menus extends PureComponent {
// 寻找选中路由
let currentMenu
let defaultSelectedKeys
for (let item of menu) {
for (let item of menuList) {
if (item.route && pathMatchRegexp(item.route, location.pathname)) {
if (!navOpenKeys.length && item.mpid && !openKeysFlag)
changeOpenKeys([String(item.mpid)])
if (!navOpenKeys.length && item.menuParentId && !openKeysFlag)
changeOpenKeys([String(item.menuParentId)])
currentMenu = item
break
}
@@ -119,7 +119,7 @@ class Menus extends PureComponent {
const getPath = item => {
if (item && item[pid]) {
if (item[pid] === '-1') {
result.unshift(String(item['bpid']))
result.unshift(String(item['breadcrumbParentId']))
} else {
result.unshift(String(item[pid]))
getPath(queryArray(array, id, item[pid]))
@@ -130,7 +130,12 @@ class Menus extends PureComponent {
return result
}
if (currentMenu) {
defaultSelectedKeys = getPathArray(menu, currentMenu, 'mpid', 'id')
defaultSelectedKeys = getPathArray(
menuList,
currentMenu,
'menuParentId',
'id'
)
}
if (!defaultSelectedKeys) {
@@ -151,7 +156,7 @@ class Menus extends PureComponent {
}
}
Menus.propTypes = {
menu: PropTypes.array,
menuList: PropTypes.array,
siderFold: PropTypes.bool,
darkTheme: PropTypes.bool,
navOpenKeys: PropTypes.array,
+3 -3
View File
@@ -16,12 +16,12 @@ class Sider extends PureComponent {
changeTheme,
navOpenKeys,
changeOpenKeys,
menu,
menuList,
i18n,
} = this.props
const menusProps = {
menu,
menuList,
siderFold,
darkTheme,
location,
@@ -57,7 +57,7 @@ class Sider extends PureComponent {
}
Sider.propTypes = {
menu: PropTypes.array,
menuList: PropTypes.array,
siderFold: PropTypes.bool,
darkTheme: PropTypes.bool,
location: PropTypes.object,
+14 -13
View File
@@ -6,10 +6,11 @@ import withRouter from 'umi/withRouter'
import { connect } from 'dva'
import { MyLayout } from 'components'
import { BackTop, Layout } from 'antd'
import { GlobalFooter } from 'ant-design-pro'
import { classnames, config, pathMatchRegexp } from 'utils'
import Error from '../pages/404'
const { Content, Footer, Sider } = Layout
const { Content, Sider } = Layout
const { Header, Bread, styles } = MyLayout
const { prefix } = config
@@ -25,12 +26,12 @@ class PrimaryLayout extends PureComponent {
isNavbar,
menuPopoverVisible,
navOpenKeys,
menu,
menuList,
permissions,
} = app
let { pathname } = location
pathname = pathname.startsWith('/') ? pathname : `/${pathname}`
const current = menu.filter(item =>
const current = menuList.filter(item =>
pathMatchRegexp(item.route || '', pathname)
)
const hasPermission = current.length
@@ -38,7 +39,7 @@ class PrimaryLayout extends PureComponent {
: false
const headerProps = {
menu,
menuList,
user,
location,
siderFold,
@@ -63,7 +64,7 @@ class PrimaryLayout extends PureComponent {
}
const siderProps = {
menu,
menuList,
location,
siderFold,
darkTheme,
@@ -84,7 +85,7 @@ class PrimaryLayout extends PureComponent {
}
const breadProps = {
menu,
menuList,
location,
}
@@ -96,26 +97,26 @@ class PrimaryLayout extends PureComponent {
[styles.light]: !darkTheme,
})}
>
{!isNavbar && (
{!isNavbar ? (
<Sider trigger={null} collapsible collapsed={siderFold}>
{siderProps.menu.length === 0 ? null : (
{siderProps.menuList.length === 0 ? null : (
<MyLayout.Sider {...siderProps} />
)}
</Sider>
)}
) : null}
<Layout
style={{ height: '100vh', overflow: 'scroll' }}
id="PrimaryLayoutContainer"
>
<BackTop
target={() => document.getElementById('PrimaryLayoutContainer')}
/>
<Header {...headerProps} />
<Content>
<Bread {...breadProps} />
{hasPermission ? children : <Error />}
</Content>
<Footer>{config.footerText}</Footer>
<BackTop
target={() => document.getElementById('PrimaryLayoutContainer')}
/>
<GlobalFooter copyright={config.copyright} />
</Layout>
</Layout>
</Fragment>
+4 -4
View File
@@ -18,7 +18,7 @@ export default {
permissions: {
visit: [],
},
menu: [
menuList: [
{
id: 1,
icon: 'laptop',
@@ -66,14 +66,14 @@ export default {
if (success && user) {
const { list } = yield call(queryMenuList)
const { permissions } = user
let menu = list
let menuList = list
if (
permissions.role === RoleType.ADMIN ||
permissions.role === RoleType.DEVELOPER
) {
permissions.visit = list.map(item => item.id)
} else {
menu = list.filter(item => {
menuList = list.filter(item => {
const cases = [
permissions.visit.includes(item.id),
item.mpid
@@ -89,7 +89,7 @@ export default {
payload: {
user,
permissions,
menu,
menuList,
},
})
if (location.pathname === '/login') {
+10 -12
View File
@@ -25,18 +25,16 @@ class User extends PureComponent {
} = user
const handleRefresh = newQuery => {
dispatch(
router.push({
pathname,
search: stringify(
{
...query,
...newQuery,
},
{ arrayFormat: 'repeat' }
),
})
)
router.push({
pathname,
search: stringify(
{
...query,
...newQuery,
},
{ arrayFormat: 'repeat' }
),
})
}
const modalProps = {