提交 c95724c3 authored 作者: vipcxj's avatar vipcxj

1.修复storybooks

2.优化lodash大小
上级 27fd7af0
{ {
"presets": [ "presets": [
"es2015", [
"es2016", "umi",
"es2017", { "browsers": ["ie >= 9"] }
"stage-0", ]
"react"
], ],
"plugins": [ "plugins": [
"dva-hmr", "dva-hmr",
"transform-runtime", "lodash",
["import", { "libraryName": "antd", "style": true }] ["import", { "libraryName": "antd", "style": true }]
] ]
} }
...@@ -3,5 +3,5 @@ import '@babel/polyfill'; ...@@ -3,5 +3,5 @@ import '@babel/polyfill';
import { configure } from '@storybook/react'; import { configure } from '@storybook/react';
import('../stories').then((stories) => { import('../stories').then((stories) => {
configure(stories, module); configure(() => stories, module);
}); });
require('../babel-register'); require('../babel-register');
const createProxy = require('http-proxy-middleware'); const createProxy = require('http-proxy-middleware');
const _ = require('lodash'); const forEach = require('lodash/forEach');
const assert = require('assert'); const assert = require('assert');
const roadhog = require('../.webpackrc'); const roadhog = require('../.webpackrc');
...@@ -40,10 +40,10 @@ function createMockHandler(value) { ...@@ -40,10 +40,10 @@ function createMockHandler(value) {
module.exports = (router) => { module.exports = (router) => {
const proxy = roadhog.env.development.proxy; const proxy = roadhog.env.development.proxy;
_.forEach(proxy, (value, key) => { forEach(proxy, (value, key) => {
router.use(key, createProxy(key, value)); router.use(key, createProxy(key, value));
}); });
_.forEach(mock, (value, key) => { forEach(mock, (value, key) => {
const parsedkey = parseKey(key); const parsedkey = parseKey(key);
assert( assert(
typeof value === 'function' || typeof value === 'function' ||
......
const genDefaultConfig = require('@storybook/react/dist/server/config/defaults/webpack.config.js').default; const genDefaultConfig = require('@storybook/react/dist/server/config/defaults/webpack.config.js');
const path = require('path').default; const path = require('path');
module.exports = (baseConfig, env) => { module.exports = (baseConfig, env) => {
const config = genDefaultConfig(baseConfig, env); const config = genDefaultConfig(baseConfig, env);
......
...@@ -27,6 +27,7 @@ module.exports = { ...@@ -27,6 +27,7 @@ module.exports = {
'menu-dark-bg': '#404040', 'menu-dark-bg': '#404040',
"layout-header-padding": "0", "layout-header-padding": "0",
}, },
browserslist: ['ie >= 9'],
ignoreMomentLocale: true, ignoreMomentLocale: true,
hash: true, hash: true,
env: { env: {
...@@ -34,6 +35,7 @@ module.exports = { ...@@ -34,6 +35,7 @@ module.exports = {
publicPath: "/", publicPath: "/",
extraBabelPlugins: [ extraBabelPlugins: [
"dva-hmr", "dva-hmr",
"lodash",
["import", { "libraryName": "antd", "style": true }] ["import", { "libraryName": "antd", "style": true }]
], ],
devtool: "cheap-module-eval-source-map", devtool: "cheap-module-eval-source-map",
...@@ -49,6 +51,7 @@ module.exports = { ...@@ -49,6 +51,7 @@ module.exports = {
apiContextPath: "/bm" apiContextPath: "/bm"
}, },
extraBabelPlugins: [ extraBabelPlugins: [
"lodash",
["import", { "libraryName": "antd", "style": true }] ["import", { "libraryName": "antd", "style": true }]
], ],
devtool: "hidden-source-map" devtool: "hidden-source-map"
......
/* eslint-disable comma-dangle */ /* eslint-disable comma-dangle */
const babel = require('@babel/register/lib/node');
const babel = require('./my-babel-register');
babel.default(({ babel.default(({
presets: [ presets: [
'es2015', ['umi', { browsers: ['ie >= 9'], commonjs: true }]
'react' ],
] plugins: [
'lodash',
['import', { libraryName: 'antd', style: true }]
],
})); }));
module.exports = { module.exports = {
unregister() { unregister() {
babel.hookExtensions([]); babel.default({
extensions: [],
});
}, },
}; };
/* eslint-disable */
exports.__esModule = true;
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _stringify = require("babel-runtime/core-js/json/stringify");
var _stringify2 = _interopRequireDefault(_stringify);
exports.default = function () {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (opts.only != null) only = _babelCore.util.arrayify(opts.only, _babelCore.util.regexify);
if (opts.ignore != null) ignore = _babelCore.util.arrayify(opts.ignore, _babelCore.util.regexify);
if (opts.extensions) hookExtensions(_babelCore.util.arrayify(opts.extensions));
if (opts.cache === false) cache = null;
delete opts.extensions;
delete opts.ignore;
delete opts.cache;
delete opts.only;
(0, _extend2.default)(transformOpts, opts);
};
var _cloneDeep = require("lodash/cloneDeep");
var _cloneDeep2 = _interopRequireDefault(_cloneDeep);
var _sourceMapSupport = require("source-map-support");
var _sourceMapSupport2 = _interopRequireDefault(_sourceMapSupport);
var _cache = require("./cache");
var registerCache = _interopRequireWildcard(_cache);
var _extend = require("lodash/extend");
var _extend2 = _interopRequireDefault(_extend);
var _babelCore = require("babel-core");
var babel = _interopRequireWildcard(_babelCore);
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_sourceMapSupport2.default.install({
handleUncaughtExceptions: false,
environment: "node",
retrieveSourceMap: function retrieveSourceMap(source) {
var map = maps && maps[source];
if (map) {
return {
url: null,
map: map
};
} else {
return null;
}
}
});
registerCache.load();
var cache = registerCache.get();
var transformOpts = {};
var ignore = void 0;
var only = void 0;
var oldHandlers = {};
var maps = {};
var cwd = process.cwd();
function getRelativePath(filename) {
return _path2.default.relative(cwd, filename);
}
function mtime(filename) {
return +_fs2.default.statSync(filename).mtime;
}
function compile(filename) {
var result = void 0;
var opts = new _babelCore.OptionManager().init((0, _extend2.default)({ sourceRoot: _path2.default.dirname(filename) }, (0, _cloneDeep2.default)(transformOpts), { filename: filename }));
var cacheKey = (0, _stringify2.default)(opts) + ":" + babel.version;
var env = process.env.BABEL_ENV || process.env.NODE_ENV;
if (env) cacheKey += ":" + env;
if (cache) {
var cached = cache[cacheKey];
if (cached && cached.mtime === mtime(filename)) {
result = cached;
}
}
if (!result) {
result = babel.transformFileSync(filename, (0, _extend2.default)(opts, {
babelrc: false,
sourceMaps: "both",
ast: false
}));
}
if (cache) {
cache[cacheKey] = result;
result.mtime = mtime(filename);
}
maps[filename] = result.map;
return result.code;
}
function shouldIgnore(filename) {
if (!ignore && !only) {
return getRelativePath(filename).split(_path2.default.sep).indexOf("node_modules") >= 0;
} else {
return _babelCore.util.shouldIgnore(filename, ignore || [], only);
}
}
function loader(m, filename) {
m._compile(compile(filename), filename);
}
function registerExtension(ext) {
var old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];
require.extensions[ext] = function (m, filename) {
if (shouldIgnore(filename)) {
old(m, filename);
} else {
loader(m, filename, old);
}
};
}
function hookExtensions(_exts) {
(0, _keys2.default)(oldHandlers).forEach(function (ext) {
var old = oldHandlers[ext];
if (old === undefined) {
delete require.extensions[ext];
} else {
require.extensions[ext] = old;
}
});
oldHandlers = {};
_exts.forEach(function (ext) {
oldHandlers[ext] = require.extensions[ext];
registerExtension(ext);
});
}
exports.hookExtensions = hookExtensions;
exports.exts = _babelCore.util.canCompile.EXTENSIONS;
hookExtensions(exports.exts);
module.exports = exports;
...@@ -35,10 +35,13 @@ ...@@ -35,10 +35,13 @@
"xml2js": "^0.4.17" "xml2js": "^0.4.17"
}, },
"devDependencies": { "devDependencies": {
"@storybook/react": "^3.2.8", "@babel/core": "^7.0.0-beta.40",
"@babel/register": "^7.0.0-beta.40",
"@storybook/react": "^3.3.15",
"babel-core": "^7.0.0-bridge.0",
"babel-plugin-dva-hmr": "^0.4.1", "babel-plugin-dva-hmr": "^0.4.1",
"babel-plugin-import": "^1.6.5", "babel-plugin-import": "^1.6.5",
"babel-register": "^7.0.0-beta.3", "babel-plugin-lodash": "^3.3.2",
"bundle-loader": "^0.5.6", "bundle-loader": "^0.5.6",
"chai": "^4.0.2", "chai": "^4.0.2",
"cross-env": "^5.1.3", "cross-env": "^5.1.3",
......
import React, { Component } from 'react'; import React, { Component } from 'react';
import { connect as dvaConnect } from 'dva'; import { connect as dvaConnect } from 'dva';
import _, { startsWith } from 'lodash'; import startsWith from 'lodash/startsWith';
import flow from 'lodash/fp/flow';
import mapKeys from 'lodash/fp/mapKeys';
import pickBy from 'lodash/fp/pickBy';
import { getApp } from '../../data/app'; import { getApp } from '../../data/app';
const connect = (modelCreator, { app, mapStateToProps, mapDispatchToProps, mergeProps, options }) => (Comp) => { const connect = (modelCreator, { app, mapStateToProps, mapDispatchToProps, mergeProps, options }) => (Comp) => {
...@@ -33,10 +36,10 @@ const connect = (modelCreator, { app, mapStateToProps, mapDispatchToProps, merge ...@@ -33,10 +36,10 @@ const connect = (modelCreator, { app, mapStateToProps, mapDispatchToProps, merge
if (state.loading) { if (state.loading) {
props.loading = state.loading; props.loading = state.loading;
props.loading.model = props.loading.models[model.namespace]; props.loading.model = props.loading.models[model.namespace];
props.loading.effect = _(props.loading.effects) props.loading.effect = flow(
.pickBy((v, k) => startsWith(k, `${model.namespace}/`)) pickBy((v, k) => startsWith(k, `${model.namespace}/`)),
.mapKeys((v, k) => k.slice(model.namespace.length + 1)) mapKeys((v, k) => k.slice(model.namespace.length + 1)),
.value(); )(props.loading.effects);
} }
return props; return props;
}; };
......
import uuid from 'uuid/v4'; import uuid from 'uuid/v4';
import _ from 'lodash'; import forEach from 'lodash/forEach';
import set from 'lodash/set';
import pickBy from 'lodash/pickBy';
import negate from 'lodash/negate';
import isUndefined from 'lodash/isUndefined';
import toPlainObject from 'lodash/toPlainObject';
import uniqueId from 'lodash/uniqueId';
import flow from 'lodash/fp/flow';
import filter from 'lodash/fp/filter';
import find from 'lodash/fp/find';
import { datasourceApi } from '../../../services/datasource'; import { datasourceApi } from '../../../services/datasource';
const prefix = uuid(); const prefix = uuid();
const getKeyName = (meta) => { const getKeyName = (meta) => {
const keyProperty = _(meta.properties || []) const keyProperty = flow(
.filter(property => !property.skip) filter(property => !property.skip),
.find(property => property.key); find(property => property.key),
)(meta.properties || []);
return keyProperty ? keyProperty.name : undefined; return keyProperty ? keyProperty.name : undefined;
}; };
...@@ -30,16 +40,16 @@ const parseMetas = (metas) => { ...@@ -30,16 +40,16 @@ const parseMetas = (metas) => {
if (!metas) { if (!metas) {
return ret; return ret;
} }
_.forEach(metas, (value, key) => { forEach(metas, (value, key) => {
let finalValue; let finalValue;
try { try {
finalValue = JSON.parse(value); finalValue = JSON.parse(value);
} catch (err) { } catch (err) {
finalValue = value; finalValue = value;
} }
_.set(ret, key, finalValue); set(ret, key, finalValue);
}); });
return _.pickBy(ret, _.negate(_.isUndefined)); return pickBy(ret, negate(isUndefined));
}; };
const makeProps = (meta) => { const makeProps = (meta) => {
...@@ -71,14 +81,14 @@ const makeColumns = (meta) => { ...@@ -71,14 +81,14 @@ const makeColumns = (meta) => {
if ((props.fixed === true || props.fixed === 'left' || props.fixed === 'right') && props.width === undefined) { if ((props.fixed === true || props.fixed === 'left' || props.fixed === 'right') && props.width === undefined) {
props.width = 150; props.width = 150;
} }
return _.pickBy({ return pickBy({
...props, ...props,
dataIndex: property.name, dataIndex: property.name,
key: property.name, key: property.name,
sorter: property.sort, sorter: property.sort,
filterType: property.filterType, filterType: property.filterType,
filterEnums: getSource(property), filterEnums: getSource(property),
}, _.negate(_.isUndefined)); }, negate(isUndefined));
}) })
.filter(c => c.visible !== false) .filter(c => c.visible !== false)
.sort((c1, c2) => { .sort((c1, c2) => {
...@@ -128,7 +138,7 @@ const getArrayData = ({ dataType, arrayData, singularData }, meta) => { ...@@ -128,7 +138,7 @@ const getArrayData = ({ dataType, arrayData, singularData }, meta) => {
.forEach((property) => { .forEach((property) => {
data.push((singularData || {})[property.name]); data.push((singularData || {})[property.name]);
}); });
return [_.toPlainObject(data)]; return [toPlainObject(data)];
} else { } else {
throw new Error(`Unsupported data type: ${dataType}`); throw new Error(`Unsupported data type: ${dataType}`);
} }
...@@ -136,7 +146,7 @@ const getArrayData = ({ dataType, arrayData, singularData }, meta) => { ...@@ -136,7 +146,7 @@ const getArrayData = ({ dataType, arrayData, singularData }, meta) => {
const modelCreator = () => { const modelCreator = () => {
const name = 'model'; const name = 'model';
const namespace = _.uniqueId(prefix); const namespace = uniqueId(prefix);
const loadMeta = function* loadMeta({ select, call, put }) { const loadMeta = function* loadMeta({ select, call, put }) {
const { coordinate } = yield select(state => state[namespace]); const { coordinate } = yield select(state => state[namespace]);
const api = datasourceApi(coordinate); const api = datasourceApi(coordinate);
......
import React, { Component } from 'react'; import React, { Component } from 'react';
import _ from 'lodash'; import castArray from 'lodash/castArray';
import noop from 'lodash/noop';
import { Table, Button, Form } from 'antd'; import { Table, Button, Form } from 'antd';
class TableInput extends Component { class TableInput extends Component {
...@@ -23,11 +24,11 @@ class TableInput extends Component { ...@@ -23,11 +24,11 @@ class TableInput extends Component {
onOk() { onOk() {
const { value, items, form, onChange } = this.props; const { value, items, form, onChange } = this.props;
const row = {}; const row = {};
_.castArray(items).forEach((item) => { castArray(items).forEach((item) => {
row[item.name] = form.getFieldValue(item.name); row[item.name] = form.getFieldValue(item.name);
}); });
if (this.state.operation === 'add') { if (this.state.operation === 'add') {
(onChange || _.noop)([...(value || []), row]); (onChange || noop)([...(value || []), row]);
} }
this.setState({ this.setState({
editing: false, editing: false,
...@@ -36,7 +37,7 @@ class TableInput extends Component { ...@@ -36,7 +37,7 @@ class TableInput extends Component {
} }
makeColumns() { makeColumns() {
const { items } = this.props; const { items } = this.props;
return _.castArray(items) return castArray(items)
.map((item) => { .map((item) => {
return { return {
...item, ...item,
...@@ -48,7 +49,7 @@ class TableInput extends Component { ...@@ -48,7 +49,7 @@ class TableInput extends Component {
} }
makeDataSource() { makeDataSource() {
const { value } = this.props; const { value } = this.props;
return _.castArray(value || []) return castArray(value || [])
.map((row, idx) => ({ .map((row, idx) => ({
...row, ...row,
__key__: idx, __key__: idx,
...@@ -58,7 +59,7 @@ class TableInput extends Component { ...@@ -58,7 +59,7 @@ class TableInput extends Component {
render() { render() {
const { items, form, children } = this.props; const { items, form, children } = this.props;
if (this.state.editing) { if (this.state.editing) {
const fields = _.castArray(children) const fields = castArray(children)
.map( .map(
(child, i) => { (child, i) => {
const item = items[i]; const item = items[i];
......
import React, { Component } from 'react'; import React, { Component } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { Checkbox, Button } from 'antd'; import { Checkbox, Button } from 'antd';
import { isString } from 'lodash'; import isString from 'lodash/isString';
import styles from './enum.less'; import styles from './enum.less';
class EnumSearch extends Component { class EnumSearch extends Component {
......
import { flatMap } from 'lodash'; import flatMap from 'lodash/flatMap';
import { fetchMenus, fetchModuleInfos, fetchModuleLayout } from '../services/modules'; import { fetchMenus, fetchModuleInfos, fetchModuleLayout } from '../services/modules';
const data = { const data = {
......
import Mock from 'mockjs'; import Mock from 'mockjs';
import moment from 'moment'; import moment from 'moment';
import _ from 'lodash'; import flatMap from 'lodash/flatMap';
const defaultDateFormat = 'YYYY-MM-DD'; const defaultDateFormat = 'YYYY-MM-DD';
const defaultTimeFormat = 'HH:mm:ss'; const defaultTimeFormat = 'HH:mm:ss';
...@@ -16,7 +16,7 @@ export function getTasks() { ...@@ -16,7 +16,7 @@ export function getTasks() {
id: idx, id: idx,
name: `流程${idx}`, name: `流程${idx}`,
})); }));
const tasks = _.flatMap(progresses, (progress) => { const tasks = flatMap(progresses, (progress) => {
const s = Random.natural(0, 100); const s = Random.natural(0, 100);
const e = Random.natural(start + 5, start + 20); const e = Random.natural(start + 5, start + 20);
return Random.range(s, e).map((idx) => { return Random.range(s, e).map((idx) => {
......
import { routerRedux } from 'dva-react-router-3/router'; import { routerRedux } from 'dva-react-router-3/router';
import { isString } from 'lodash'; import isString from 'lodash/isString';
import { logout } from '../../services/main'; import { logout } from '../../services/main';
import { fetchDomains, switchDomain, currentDomain } from '../../services/domain'; import { fetchDomains, switchDomain, currentDomain } from '../../services/domain';
import { getMenus, getModuleInfo } from '../../data/modules'; import { getMenus, getModuleInfo } from '../../data/modules';
......
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { Router } from 'dva-react-router-3/router'; import { Router } from 'dva-react-router-3/router';
import { isString } from 'lodash'; import isString from 'lodash/isString';
import config from './utils/config'; import config from './utils/config';
import { isAuthed, hasDomain, histories } from './utils/auth'; import { isAuthed, hasDomain, histories } from './utils/auth';
import { fullPath, makePromise0 } from './utils/helper'; import { fullPath, makePromise0 } from './utils/helper';
......
import { mapKeys, toPairs, isUndefined, isString, partial } from 'lodash'; import mapKeys from 'lodash/mapKeys';
import toPairs from 'lodash/toPairs';
import isUndefined from 'lodash/isUndefined';
import isString from 'lodash/isString';
import partial from 'lodash/partial';
import request from '../utils/request'; import request from '../utils/request';
import post from '../utils/post'; import post from '../utils/post';
import { normParams } from '../utils/http-helper'; import { normParams } from '../utils/http-helper';
......
import { browserHistory } from 'dva-react-router-3/router'; import { browserHistory } from 'dva-react-router-3/router';
import resolvePathname from 'resolve-pathname'; import resolvePathname from 'resolve-pathname';
import { isString } from 'lodash'; import isString from 'lodash/isString';
import config from '../utils/config'; import config from '../utils/config';
const { contextPath } = config; const { contextPath } = config;
......
import _, { partial } from 'lodash'; import partial from 'lodash/partial';
import _ from 'lodash/fp/placeholder';
import request from '../utils/request'; import request from '../utils/request';
import post from '../utils/post'; import post from '../utils/post';
import doDelete from '../utils/delete'; import doDelete from '../utils/delete';
......
import { partial } from 'lodash'; import partial from 'lodash/partial';
import request from '../utils/request'; import request from '../utils/request';
import post from '../utils/post'; import post from '../utils/post';
import config from '../utils/config'; import config from '../utils/config';
......
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import { isNil, defaults } from 'lodash'; import isNil from 'lodash/isNil';
import defaults from 'lodash/defaults';
import { fetch } from './polyfill'; import { fetch } from './polyfill';
import { checkStatus, normParams, parseObject } from './http-helper'; import { checkStatus, normParams, parseObject } from './http-helper';
import middleware from './middleware'; import middleware from './middleware';
......
import moment from 'moment'; import moment from 'moment';
import _ from 'lodash'; import pickBy from 'lodash/pickBy';
import negate from 'lodash/negate';
import isUndefined from 'lodash/isUndefined';
import { createJSEncrypt } from './jsencrypt'; import { createJSEncrypt } from './jsencrypt';
import config from './config'; import config from './config';
...@@ -118,6 +120,6 @@ export function makePromise1(thunk) { ...@@ -118,6 +120,6 @@ export function makePromise1(thunk) {
} }
export function filterValidParams(params) { export function filterValidParams(params) {
return _.pickBy(params, _.negate(_.isUndefined)); return pickBy(params, negate(isUndefined));
} }
import _ from 'lodash'; import isPlainObject from 'lodash/isPlainObject';
import isObjectLike from 'lodash/isObjectLike';
import isArray from 'lodash/isArray';
import isNumber from 'lodash/isNumber';
import isBoolean from 'lodash/isBoolean';
import isNull from 'lodash/isNull';
import isUndefined from 'lodash/isUndefined';
import isNil from 'lodash/isNil';
import map from 'lodash/map';
import mapValues from 'lodash/mapValues';
import curry from 'lodash/curry';
import flow from 'lodash/fp/flow';
import toPairs from 'lodash/fp/toPairs';
import flatMap from 'lodash/fp/flatMap';
import _ from 'lodash/fp/placeholder';
import { Resolver } from 'fastjson_ref_resolver'; import { Resolver } from 'fastjson_ref_resolver';
export function checkStatus(response) { export function checkStatus(response) {
...@@ -13,8 +27,11 @@ export function checkStatus(response) { ...@@ -13,8 +27,11 @@ export function checkStatus(response) {
} }
export function normParams(unnormed) { export function normParams(unnormed) {
if (_.isPlainObject(unnormed)) { if (isPlainObject(unnormed)) {
return _(unnormed).toPairs().flatMap(([k, v]) => (_.isArray(v) ? v.map(vv => [k, vv]) : [[k, v]])).value(); return flow(
toPairs,
flatMap(([k, v]) => (isArray(v) ? v.map(vv => [k, vv]) : [[k, v]])),
)(unnormed);
} else { } else {
return unnormed; return unnormed;
} }
...@@ -29,29 +46,29 @@ export function parseObject(response, middleware, { num2str = false, bool2str = ...@@ -29,29 +46,29 @@ export function parseObject(response, middleware, { num2str = false, bool2str =
if (contentType) { if (contentType) {
const needMap = num2str || bool2str || nul2str || ud2str || nil2str; const needMap = num2str || bool2str || nul2str || ud2str || nil2str;
const mapStr = (value) => { const mapStr = (value) => {
if (num2str && _.isNumber(value)) { if (num2str && isNumber(value)) {
return value.toString(); return value.toString();
} }
if (bool2str && _.isBoolean(value)) { if (bool2str && isBoolean(value)) {
return value.toString(); return value.toString();
} }
if (nul2str && _.isNull(value)) { if (nul2str && isNull(value)) {
return ''; return '';
} }
if (ud2str && _.isUndefined(value)) { if (ud2str && isUndefined(value)) {
return ''; return '';
} }
if (nil2str && _.isNil(value)) { if (nil2str && isNil(value)) {
return ''; return '';
} }
return value; return value;
}; };
const mapObj = (obj, mapArrFunc) => { const mapObj = (obj, mapArrFunc) => {
if (_.isArray(obj)) { if (isArray(obj)) {
return mapArrFunc(obj, mapObj); return mapArrFunc(obj, mapObj);
} }
if (_.isPlainObject(obj)) { if (isPlainObject(obj)) {
return _.mapValues(obj, (val) => { return mapValues(obj, (val) => {
const ret = mapStr(val); const ret = mapStr(val);
return mapObj(ret, mapArrFunc); return mapObj(ret, mapArrFunc);
}); });
...@@ -59,23 +76,23 @@ export function parseObject(response, middleware, { num2str = false, bool2str = ...@@ -59,23 +76,23 @@ export function parseObject(response, middleware, { num2str = false, bool2str =
return obj; return obj;
}; };
const mapArr = (arr, mapObjFunc) => { const mapArr = (arr, mapObjFunc) => {
if (_.isPlainObject(arr)) { if (isPlainObject(arr)) {
return mapObjFunc(arr, mapArr); return mapObjFunc(arr, mapArr);
} }
if (_.isArray(arr)) { if (isArray(arr)) {
return _.map(arr, (val) => { return map(arr, (val) => {
const ret = mapStr(val); const ret = mapStr(val);
return mapArr(ret, mapObjFunc); return mapArr(ret, mapObjFunc);
}); });
} }
return arr; return arr;
}; };
const mapValue = _.curry(mapObj)(_, mapArr); const mapValue = curry(mapObj)(_, mapArr);
if (contentType.indexOf('json') !== -1) { if (contentType.indexOf('json') !== -1) {
return response.json() return response.json()
.then((json) => { .then((json) => {
let out = json; let out = json;
if (_.isObjectLike(out)) { if (isObjectLike(out)) {
out = new Resolver(out).resolve(); out = new Resolver(out).resolve();
} }
return middleware ? middleware(out) : out; return middleware ? middleware(out) : out;
...@@ -84,17 +101,14 @@ export function parseObject(response, middleware, { num2str = false, bool2str = ...@@ -84,17 +101,14 @@ export function parseObject(response, middleware, { num2str = false, bool2str =
return needMap ? mapValue(data) : data; return needMap ? mapValue(data) : data;
}); });
} else if (contentType.indexOf('xml') !== -1) { } else if (contentType.indexOf('xml') !== -1) {
return response.text() return Promise.all([response.text(), import('xml2js')])
.then((text) => { .then(([text, xml2js]) => {
return require.ensure([], (require) => { const { parseString } = xml2js;
const { parseString } = require('xml2js'); return JSON.parse(parseString(text, {}));
const options = {};
return JSON.parse(parseString(text, options));
});
}) })
.then((json) => { .then((json) => {
let out = json; let out = json;
if (_.isObjectLike(out)) { if (isObjectLike(out)) {
out = new Resolver(out).resolve(); out = new Resolver(out).resolve();
} }
return middleware ? middleware(out) : out; return middleware ? middleware(out) : out;
......
import _ from 'lodash'; import isString from 'lodash/isString';
import get from 'lodash/get';
const { isString, get, sortBy } = _; import flow from 'lodash/fp/flow';
import sortBy from 'lodash/fp/sortBy';
import reverse from 'lodash/fp/reverse';
/** /**
* @callback KeyExtractor * @callback KeyExtractor
...@@ -74,9 +76,12 @@ export const toHistogram = (array, key, order = 'desc') => { ...@@ -74,9 +76,12 @@ export const toHistogram = (array, key, order = 'desc') => {
} }
switch (order) { switch (order) {
case 'desc': case 'desc':
return _(res).sortBy(v => v.num).reverse().value(); return flow(
sortBy(v => v.num),
reverse,
)(res);
case 'asc': case 'asc':
return sortBy(res, v => v.num); return sortBy(v => v.num, res);
default: default:
throw new Error(`unsupported order: ${order}`); throw new Error(`unsupported order: ${order}`);
} }
......
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import { isNil, defaults } from 'lodash'; import isNil from 'lodash/isNil';
import defaults from 'lodash/defaults';
import { fetch } from './polyfill'; import { fetch } from './polyfill';
import { checkStatus, normParams, parseObject } from './http-helper'; import { checkStatus, normParams, parseObject } from './http-helper';
import middleware from './middleware'; import middleware from './middleware';
......
import { isNil, defaults } from 'lodash'; import isNil from 'lodash/isNil';
import defaults from 'lodash/defaults';
import { fetch } from './polyfill'; import { fetch } from './polyfill';
import { checkStatus, normParams, parseObject } from './http-helper'; import { checkStatus, normParams, parseObject } from './http-helper';
import middleware from './middleware'; import middleware from './middleware';
......
import React from 'react'; import React from 'react';
import { partial } from 'lodash'; import partial from 'lodash/partial';
import { storiesOf } from '@storybook/react'; import { storiesOf } from '@storybook/react';
import ReactJson from 'react-json-view'; import ReactJson from 'react-json-view';
...@@ -12,14 +12,16 @@ import TableInput from '../src/components/table/input-table'; ...@@ -12,14 +12,16 @@ import TableInput from '../src/components/table/input-table';
import UCA from '../src/components/uca'; import UCA from '../src/components/uca';
import { makeCancelable } from '../src/utils/promise'; import { makeCancelable } from '../src/utils/promise';
import { login } from '../src/services/login'; import { login, authorize } from '../src/services/login';
import { validate } from '../src/services/login/password'; import { validate } from '../src/services/login/password';
import { switchDomain } from '../src/services/domain'; import { switchDomain } from '../src/services/domain';
import { setToken } from '../src/utils/auth'; import { setToken } from '../src/utils/auth';
import { encrypt } from '../src/utils/helper';
const loginIt = async (userName, password, domainPath) => { const loginIt = async (userName, password, domainPath) => {
const result = await login({ type: 'userName', data: userName, authRequest: await validate(password) }); const { tokenId } = await login({ type: 'userName', data: userName });
const { tokenId } = result; const authRequest = await validate(password, encrypt(tokenId));
await authorize(authRequest);
await setToken(tokenId); await setToken(tokenId);
await switchDomain(domainPath); await switchDomain(domainPath);
}; };
......
const { JSDOM } = require('jsdom'); const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>'); const jsdom = new JSDOM('<!doctype html><html><body/></html>');
const { window } = jsdom; const { window } = jsdom;
window.matchMedia = window.matchMedia || function () { window.matchMedia = window.matchMedia || function matchMedia() {
return { return {
matches: false, matches: false,
addListener() {}, addListener() {},
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论