From 5aa187334a6ca7c4fedffc30ce1b8277a37622ff Mon Sep 17 00:00:00 2001 From: zuiidea Date: Mon, 17 Sep 2018 20:54:06 +0800 Subject: [PATCH] Optimize mock related files and variable names. --- mock/_utils.js | 40 ++++++++++++++++++++++++++ mock/common.js | 48 +++++++++++++++++-------------- mock/dashboard.js | 9 ++---- mock/menu.js | 42 +++++++++++++-------------- mock/post.js | 50 ++++++++++++++++++++++++++++----- mock/user.js | 24 ++++++++-------- src/components/Layout/Bread.js | 16 +++++------ src/components/Layout/Header.js | 6 ++-- src/components/Layout/Menu.js | 27 ++++++++++-------- src/components/Layout/Sider.js | 6 ++-- src/layouts/PrimaryLayout.js | 27 +++++++++--------- src/models/app.js | 8 +++--- src/pages/user/index.js | 22 +++++++-------- 13 files changed, 203 insertions(+), 122 deletions(-) create mode 100644 mock/_utils.js diff --git a/mock/_utils.js b/mock/_utils.js new file mode 100644 index 0000000..9ad83ee --- /dev/null +++ b/mock/_utils.js @@ -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' diff --git a/mock/common.js b/mock/common.js index 1d5436d..f4c26b6 100644 --- a/mock/common.js +++ b/mock/common.js @@ -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) + ) }, }, ], diff --git a/mock/dashboard.js b/mock/dashboard.js index 7522252..3b263ea 100644 --- a/mock/dashboard.js +++ b/mock/dashboard.js @@ -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) }, } diff --git a/mock/menu.js b/mock/menu.js index 4df12cb..25c663d 100644 --- a/mock/menu.js +++ b/mock/menu.js @@ -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) }, } diff --git a/mock/post.js b/mock/post.js index 002fa19..e8e0d7c 100644 --- a/mock/post.js +++ b/mock/post.js @@ -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 }) diff --git a/mock/user.js b/mock/user.js index e841acd..5b57a09 100644 --- a/mock/user.js +++ b/mock/user.js @@ -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 diff --git a/src/components/Layout/Bread.js b/src/components/Layout/Bread.js index d15d79e..a5c6f6b 100644 --- a/src/components/Layout/Bread.js +++ b/src/components/Layout/Bread.js @@ -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`, diff --git a/src/components/Layout/Header.js b/src/components/Layout/Header.js index f9ee162..a16843e 100644 --- a/src/components/Layout/Header.js +++ b/src/components/Layout/Header.js @@ -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, diff --git a/src/components/Layout/Menu.js b/src/components/Layout/Menu.js index 4c63a61..d85ea53 100644 --- a/src/components/Layout/Menu.js +++ b/src/components/Layout/Menu.js @@ -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 ( { 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, diff --git a/src/components/Layout/Sider.js b/src/components/Layout/Sider.js index 17c55db..474b05f 100644 --- a/src/components/Layout/Sider.js +++ b/src/components/Layout/Sider.js @@ -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, diff --git a/src/layouts/PrimaryLayout.js b/src/layouts/PrimaryLayout.js index 73d2815..ae0e047 100644 --- a/src/layouts/PrimaryLayout.js +++ b/src/layouts/PrimaryLayout.js @@ -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 ? ( - {siderProps.menu.length === 0 ? null : ( + {siderProps.menuList.length === 0 ? null : ( )} - )} + ) : null} - document.getElementById('PrimaryLayoutContainer')} - />
{hasPermission ? children : } -
{config.footerText}
+ document.getElementById('PrimaryLayoutContainer')} + /> + diff --git a/src/models/app.js b/src/models/app.js index 096fa2b..04e39e6 100644 --- a/src/models/app.js +++ b/src/models/app.js @@ -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') { diff --git a/src/pages/user/index.js b/src/pages/user/index.js index d42fc0a..5c793c1 100644 --- a/src/pages/user/index.js +++ b/src/pages/user/index.js @@ -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 = {