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

fix: 箭头函数中使用arguments存在未知bug,用...args代替

improve: 1.去除由lowdb引起的lodash整体间接依赖,减小包大小;2.使用动态import代替动态require
上级 c95724c3
...@@ -11,5 +11,6 @@ ...@@ -11,5 +11,6 @@
.DS_Store .DS_Store
npm-debug.log* npm-debug.log*
/.idea
/storybook-static /storybook-static
jsCodeStructure.html
...@@ -52,6 +52,7 @@ ...@@ -52,6 +52,7 @@
"jsdom": "^11.0.0", "jsdom": "^11.0.0",
"less": "^2.7.2", "less": "^2.7.2",
"less-loader": "^4.0.0", "less-loader": "^4.0.0",
"lodash-webpack-plugin": "^0.11.4",
"mockjs": "^1.0.1-beta3", "mockjs": "^1.0.1-beta3",
"path": "^0.12.7", "path": "^0.12.7",
"react-test-renderer": "^16.2.0", "react-test-renderer": "^16.2.0",
......
...@@ -4,7 +4,7 @@ import { Router } from 'dva-react-router-3/router'; ...@@ -4,7 +4,7 @@ import { Router } from 'dva-react-router-3/router';
import isString from 'lodash/isString'; 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 } from './utils/helper';
import { processError } from './utils/error'; import { processError } from './utils/error';
import App from './routes/app'; import App from './routes/app';
import { getMenus, getModuleInfo, getModuleLayout } from './data/modules'; import { getMenus, getModuleInfo, getModuleLayout } from './data/modules';
...@@ -89,10 +89,10 @@ const createRoutes = async (app, modules, groups, basePath) => { ...@@ -89,10 +89,10 @@ const createRoutes = async (app, modules, groups, basePath) => {
name: showName, name: showName,
}; };
if (layout.route) { if (layout.route) {
const modelBundle = await makePromise0(require('bundle-loader!./models/main/modules/' + layout.route + '/index.js').default); // eslint-disable-line import/no-dynamic-require, prefer-template, global-require const modelBundle = await import(`./models/main/modules/${layout.route}`);
registerModel(app, modelBundle); registerModel(app, modelBundle.default);
const routeBundle = await makePromise0(require('bundle-loader!./routes/main/modules/' + layout.route + '/index.js').default); // eslint-disable-line import/no-dynamic-require, prefer-template, global-require const routeBundle = await import(`./routes/main/modules/${layout.route}`);
route.component = routeBundle; route.component = routeBundle.default;
if (routeBundle.route) { if (routeBundle.route) {
for (const key in routeBundle.route) { for (const key in routeBundle.route) {
// noinspection JSUnfilteredForInLoop // noinspection JSUnfilteredForInLoop
...@@ -177,10 +177,13 @@ function RouterConfig({ history, app }) { ...@@ -177,10 +177,13 @@ function RouterConfig({ history, app }) {
{ {
path: 'login', path: 'login',
getComponent(ignored, cb) { getComponent(ignored, cb) {
require.ensure([], (require) => { Promise.all([
registerModel(app, require('./models/login').default); import('./models/login'),
cb(null, require('./routes/login').default); import('./routes/login'),
}, 'login'); ]).then(([model, route]) => {
registerModel(app, model.default);
cb(null, route.default);
});
}, },
}, },
{ {
...@@ -189,10 +192,13 @@ function RouterConfig({ history, app }) { ...@@ -189,10 +192,13 @@ function RouterConfig({ history, app }) {
maybeLogin(replace).then(() => cb()).catch(err => cb(err)); maybeLogin(replace).then(() => cb()).catch(err => cb(err));
}, },
getComponent(ignored, cb) { getComponent(ignored, cb) {
require.ensure([], (require) => { Promise.all([
registerModel(app, require('./models/domain').default); import('./models/domain'),
cb(null, require('./routes/domain').default); import('./routes/domain'),
}, 'domain'); ]).then(([model, route]) => {
registerModel(app, model.default);
cb(null, route.default);
});
}, },
}, },
{ {
...@@ -201,10 +207,13 @@ function RouterConfig({ history, app }) { ...@@ -201,10 +207,13 @@ function RouterConfig({ history, app }) {
authenticated(replace).then(() => cb()).catch(err => cb(err)); authenticated(replace).then(() => cb()).catch(err => cb(err));
}, },
getComponent(ignored, cb) { getComponent(ignored, cb) {
require.ensure([], (require) => { Promise.all([
registerModel(app, require('./models/main').default); import('./models/main'),
cb(null, require('./routes/main').default); import('./routes/main'),
}, 'main'); ]).then(([model, route]) => {
registerModel(app, model.default);
cb(null, route.default);
});
}, },
getChildRoutes: (nextState, cb) => { getChildRoutes: (nextState, cb) => {
getMenus() getMenus()
...@@ -232,10 +241,13 @@ function RouterConfig({ history, app }) { ...@@ -232,10 +241,13 @@ function RouterConfig({ history, app }) {
authenticated(replace).then(() => cb()).catch(err => cb(err)); authenticated(replace).then(() => cb()).catch(err => cb(err));
}, },
getComponent(ignored, cb) { getComponent(ignored, cb) {
require.ensure([], (require) => { Promise.all([
registerModel(app, require('./models/main/modules/' + config.fastNavigationPage).default); // eslint-disable-line import/no-dynamic-require, prefer-template import(`./models/main/modules/${config.fastNavigationPage}`),
cb(null, require('./routes/main/modules/' + config.fastNavigationPage).default); // eslint-disable-line import/no-dynamic-require, prefer-template import(`./routes/main/modules/${config.fastNavigationPage}`),
}, 'fastNav'); ]).then(([model, route]) => {
registerModel(app, model.default);
cb(null, route.default);
});
}, },
}); });
} }
......
...@@ -79,16 +79,16 @@ export class Query { ...@@ -79,16 +79,16 @@ export class Query {
* modify_time: 上一次修改时间, * modify_time: 上一次修改时间,
* uri: 资源定位符 * uri: 资源定位符
*/ */
setOrder = () => { setOrder = (...args) => {
const argn = arguments.length; const argn = args.length;
if (argn > 0) { if (argn > 0) {
this.orders = []; this.orders = [];
let lastOrder; let lastOrder;
for (let i = 0; i < argn; ++i) { for (let i = 0; i < argn; ++i) {
if (lastOrder !== undefined && (typeof arguments[i] === 'boolean')) { if (lastOrder !== undefined && (typeof args[i] === 'boolean')) {
this.orders.push({ this.orders.push({
target: lastOrder, target: lastOrder,
asc: arguments[i], asc: args[i],
}); });
lastOrder = undefined; lastOrder = undefined;
} else if (lastOrder !== undefined) { } else if (lastOrder !== undefined) {
...@@ -96,9 +96,9 @@ export class Query { ...@@ -96,9 +96,9 @@ export class Query {
target: lastOrder, target: lastOrder,
asc: true, asc: true,
}); });
lastOrder = arguments[i]; lastOrder = args[i];
} else { } else {
lastOrder = arguments[i]; lastOrder = args[i];
} }
} }
if (lastOrder !== undefined) { if (lastOrder !== undefined) {
......
...@@ -60,7 +60,7 @@ export async function hasDomain() { ...@@ -60,7 +60,7 @@ export async function hasDomain() {
return getDomain().then(result => !!result); return getDomain().then(result => !!result);
} }
const normHistory = (history, size) => { const normHistory = size => (history) => {
if (!history) { if (!history) {
history = {}; history = {};
} }
...@@ -109,58 +109,56 @@ const prev = (i, size) => { ...@@ -109,58 +109,56 @@ const prev = (i, size) => {
export const histories = { export const histories = {
async getLatest(name) { async getLatest(name) {
let history = await db.get(`history.${name}`).value(); return db(`history.${name}`)(normHistory(), (history) => {
history = normHistory(history); if (history.empty) {
if (history.empty) { return null;
return null; }
} return history.data[prev(history.top, history.size)];
return history.data[prev(history.top, history.size)]; });
}, },
async createHistory(name, size) { async createHistory(name, size) {
let history = db.get(`history.${name}`).value(); return db(`history.${name}`).write(normHistory(size));
history = normHistory(history, size);
return db.set(`history.${name}`, history).write();
}, },
async destroyHistory(name) { async destroyHistory(name) {
return db.unset(`history.${name}`).write(); return db(`history.${name}`).delete();
}, },
async getHistory(name, size) { async getHistory(name, size) {
let history = db.get(`history.${name}`).value(); return db(`history.${name}`)(normHistory(size), (h) => {
history = normHistory(history, size); if (h.empty) {
if (history.empty) { return [];
return []; } else if (h.top > h.start) {
} else if (history.top > history.start) { return h.data.slice(h.start, h.top);
return history.data.slice(history.start, history.top); } else {
} else { return [...h.data.slice(h.start, h.size), ...h.data.slice(0, h.top)];
return [...history.data.slice(history.start, history.size), ...history.data.slice(0, history.top)]; }
} });
}, },
async pushHistory(name, value, size) { async pushHistory(name, value, size) {
let history = await db.get(`history.${name}`).value(); return db(`history.${name}`).write(normHistory(size), (history) => {
history = normHistory(history, size); history.data[history.top] = value;
history.data[history.top] = value; const nextPos = next(history.top, history.size);
const nextPos = next(history.top, history.size); if (!history.empty && history.start === history.top) {
if (!history.empty && history.start === history.top) { history.top = history.start = nextPos;
history.top = history.start = nextPos; } else {
} else { history.top = nextPos;
history.top = nextPos; }
} if (history.empty) {
if (history.empty) { history.empty = false;
history.empty = false; }
} return history;
return db.set(`history.${name}`, history).write(); });
}, },
async popHistory(name) { async popHistory(name) {
let history = await db.get(`history.${name}`).value(); return db(`history.${name}`).write(normHistory(), (history) => {
history = normHistory(history); if (history.empty) {
if (history.empty) { return;
return; }
} history.top = prev(history.top, history.size);
history.top = prev(history.top, history.size); if (history.top === history.start) {
if (history.top === history.start) { history.empty = true;
history.empty = true; }
} return history;
return db.set(`history.${name}`, history).write(); });
}, },
async init() { async init() {
return db.read(); return db.read();
......
/* eslint-disable no-param-reassign */
/** @module utils/db */ /** @module utils/db */
import low from 'lowdb'; import flow from 'lodash/flow';
import get from 'lodash/get';
import set from 'lodash/set';
import unset from 'lodash/unset';
import LocalStorage from 'lowdb/adapters/LocalStorage'; import LocalStorage from 'lowdb/adapters/LocalStorage';
import { isPromise } from './helper';
const adapter = new LocalStorage('db'); // eslint-disable-next-line no-underscore-dangle
const _adapter_ = new LocalStorage('db');
/** /**
* @typedef {Object} DB * @param {CreateDB} db
* @template {T} * @param key
* @param adapter
* @return {*}
*/ */
const init = function init(db, key, adapter) {
db.read = () => {
const r = adapter.read();
return isPromise(r) ? r.then(db.plant) : db.plant(r);
};
db.write = (...args) => {
const value = args.length > 0 && args[0] !== undefined ? args[0] : db.getState();
const w = adapter.write(db.getState());
return isPromise(w) ? w.then(() => {
return value;
}) : value;
};
db.plant = (state) => {
db[key] = state;
return db;
};
db.getState = () => {
return db[key];
};
db.setState = (state) => {
db.plant(state);
return db;
};
return db.read();
};
/** /**
* @member {Function} DB~get * @typedef {Function} CreateDB
* @param {Array.<string>|string} path * @param {string} path
* @param {*} [defaultValue] * @param {*} [defaultValue]
* @return {DB.<*>} * @return {DB}
*/ */
/** /**
* @member {Function} DB~set * @member {Function} CreateDB~read
* @param {Array.<string>|string} path * @return {*|Promise.<*>}
* @param value
* @return {DB}
*/ */
/** /**
* @member {Function} DB~find * @member {Function} CreateDB~write
* @template {T} * @param {*} [state]
* @param {Function} [predicate=_.identity] * @return {*|Promise.<*>}
* @param {number} [fromIndex=0]
* @return {DB.<T>}
*/ */
/** /**
* @member {Function} DB~unset * @member {Function} CreateDB~plant
* @param {Array.<string>|string} path * @param {*} state
* @return {DB.<boolean>} * @return {CreateDB}
*/ */
/** /**
* @member {Function} DB~read * @member {Function} CreateDB~getState
* @return {Promise.<*>} * @return {*}
*/
/**
* @member {Function} CreateDB~setState
* @param {*} state
* @return {CreateDB}
*/
/**
* @typedef {Function} DB
* @param {...Function} functions
* @return {*}
*/ */
/** /**
* @member {Function} DB~write * @member {Function} DB~write
* @return {Promise.<*>} * @param {...Function} functions
* @return {*|Promise.<*>}
*/ */
/** /**
* @member {Function} DB~value * @member {Function} DB~delete
* @template {T} * @return {*|Promise.<*>}
* @return {Promise.<T>}
*/ */
/** /**
* @type {DB.<*>} * @return {CreateDB}
*/ */
const db = low(adapter); const CreateDB = () => {
function db(path, defaultValue) {
function getValue(...functions) {
const result = get(db.getState(), path, defaultValue);
return flow(...functions)(result);
}
getValue.write = (...args) => {
const result = getValue(...args);
set(db.getState(), path, result);
return db.write();
};
getValue.delete = (flush = true) => {
unset(db.getState(), path);
return flush ? db.write() : db.getState();
};
return getValue;
}
export default db; return init(db, '__state__', _adapter_);
};
export default CreateDB();
...@@ -123,3 +123,6 @@ export function filterValidParams(params) { ...@@ -123,3 +123,6 @@ export function filterValidParams(params) {
return pickBy(params, negate(isUndefined)); return pickBy(params, negate(isUndefined));
} }
export function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
import { authorize, login } from '../../src/services/login';
import { switchDomain } from '../../src/services/domain';
import { encrypt } from '../../src/utils/helper';
import { validate } from '../../src/services/login/password';
import { setToken } from '../../src/utils/auth';
export default async function (userName, password, domainPath) {
const { tokenId } = await login({ type: 'userName', data: userName });
const authRequest = await validate(password, encrypt(tokenId));
await authorize(authRequest);
await setToken(tokenId);
if (domainPath) {
await switchDomain(domainPath);
}
}
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
module.exports = function webpack(config) { module.exports = function webpack(config) {
console.log(config);
config.module.rules.push({ config.module.rules.push({
test: /\.ejs$/, test: /\.ejs$/,
loader: 'ejs-loader', loader: 'ejs-loader',
}); });
// config.plugins.push(
// new LodashModuleReplacementPlugin(),
// );
return config; return config;
}; };
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论