Skip to content

Commit

Permalink
fix: 重复请求优化
Browse files Browse the repository at this point in the history
  • Loading branch information
mengsixing committed May 16, 2019
1 parent f6e9326 commit b5d1cb4
Show file tree
Hide file tree
Showing 15 changed files with 112 additions and 67 deletions.
72 changes: 54 additions & 18 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"graphql-tag": "^2.10.1",
"html-webpack-plugin": "^3.2.0",
"koa": "^2.7.0",
"koa-body": "^4.1.0",
"koa-router": "^7.4.0",
"koa-static": "^5.0.0",
"koa2-cors": "^2.0.6",
Expand Down
19 changes: 12 additions & 7 deletions src/client/containers/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ import { withRouter } from 'react-router-dom';
import { RouteComponentProps } from 'react-router';
import renderRouters from '../router';
import Notice from '../components/Notice';
import AppContextProvider from '../context/appContextProvider';
import { tabKeyRouterMap, GITHUB_URL, COPYRIGHT } from '../constants';
import util from '../utils';
import './App.less';
import { requestPvs } from '../utils/request';
import { requestPvs, requestData } from '../utils/request';
import { AppContext } from '../context/appContext';

const { Header, Footer } = Layout;

const { useState, useEffect } = React;
const { useState, useEffect, useContext } = React;

const App: React.FunctionComponent<RouteComponentProps> = ({
history,
Expand All @@ -22,14 +22,21 @@ const App: React.FunctionComponent<RouteComponentProps> = ({
const gotoGithub = () => {
window.location.href = GITHUB_URL;
};
const appState = useContext(AppContext);
const [pvs, changePvs] = useState(0);

useEffect(() => {
// 获取 pv
requestPvs(
(pvNumber: number): void => {
changePvs(pvNumber);
}
);
// 获取房源信息
const year = tabKeyRouterMap[location.pathname];
requestData(year, (allHouses: cdFang.IhouseData[]) => {
appState.changeData(allHouses);
});
}, []);

// 根据理由选中对应 menu 项
Expand All @@ -41,10 +48,8 @@ const App: React.FunctionComponent<RouteComponentProps> = ({

// 获取年份列表
const yearList = util.getYearList();
console.warn(location, history);

return (
<AppContextProvider>
<div>
<BackTop />
<Layout>
<Header style={{ backgroundColor: 'white' }}>
Expand Down Expand Up @@ -77,7 +82,7 @@ const App: React.FunctionComponent<RouteComponentProps> = ({
{renderRouters()}
<Footer style={{ textAlign: 'center' }}>{COPYRIGHT}</Footer>
</Layout>
</AppContextProvider>
</div>
);
};

Expand Down
12 changes: 2 additions & 10 deletions src/client/containers/CurrentYear.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,19 @@ import StatisticCard from '../components/StatisticCard';
import BasicColumnGraph from '../components/BasicColumnGraph';
import { AppContext } from '../context/appContext';
import * as constants from '../constants';
import { requestData } from '../utils/request';

const { useEffect, useContext } = React;
const { useContext } = React;
const { Content } = Layout;
const { TabPane } = Tabs;

const CurrentYear: React.FunctionComponent<RouteComponentProps> = props => {
const CurrentYear: React.FunctionComponent<RouteComponentProps> = () => {
const appState = useContext(AppContext);
const { allData } = appState;

const changeTab = (activityKey: string): void => {
appState.changeActivityKey(activityKey);
};

useEffect(() => {
const year = constants.tabKeyRouterMap[props.location.pathname];
requestData(year, (allHouses: cdFang.IhouseData[]) => {
appState.changeData(allHouses);
});
}, []);

const areasGroup = _.groupBy(allData, (item: cdFang.IhouseData) => item.area);
const areasList = Object.keys(areasGroup);
const tabpanels = util.sortArea(areasList).map((item: string) => (
Expand Down
9 changes: 1 addition & 8 deletions src/client/containers/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,9 @@ interface ImonthBuilder {
[constants.BUILDER_NUMBER]: number;
}

const Home: React.FunctionComponent<RouteComponentProps> = props => {
const Home: React.FunctionComponent<RouteComponentProps> = () => {
const appState = useContext(AppContext);

useEffect(() => {
const year = constants.tabKeyRouterMap[props.location.pathname];
requestData(year, (allHouses: cdFang.IhouseData[]) => {
appState.changeData(allHouses);
});
}, []);

// 构建区域图需要的数据
const arrayByDay = _.groupBy(appState.allData, item => {
return dayjs(item.beginTime).format('YYYY-MM');
Expand Down
12 changes: 2 additions & 10 deletions src/client/containers/PastYear.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,20 @@ import StatisticCard from '../components/StatisticCard/past';
import BasicColumnGraph from '../components/BasicColumnGraph';
import { AppContext } from '../context/appContext';
import * as constants from '../constants';
import { requestData } from '../utils/request';

const { useEffect, useContext } = React;
const { useContext } = React;

const { Content } = Layout;
const { TabPane } = Tabs;

const PastYear: React.FunctionComponent<RouteComponentProps> = props => {
const PastYear: React.FunctionComponent<RouteComponentProps> = () => {
const appState = useContext(AppContext);
const { allData } = appState;

const changeTab = (activityKey: string): void => {
appState.changeActivityKey(activityKey);
};

useEffect(() => {
const year = constants.tabKeyRouterMap[props.location.pathname];
requestData(year, (allHouses: cdFang.IhouseData[]) => {
appState.changeData(allHouses);
});
}, []);

const areasGroup = _.groupBy(allData, (item: cdFang.IhouseData) => item.area);
const areasList = Object.keys(areasGroup);
const tabpanels = util.sortArea(areasList).map((item: string) => (
Expand Down
9 changes: 6 additions & 3 deletions src/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import Loading from './components/Loading';
import AppContextProvider from './context/appContextProvider';

const { lazy, Suspense } = React;

const App = lazy(() => import('./containers/App'));

ReactDOM.render(
<Suspense fallback={<Loading height="100vh" tip="页面加载中..." />}>
<BrowserRouter>
<App />
</BrowserRouter>
<AppContextProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</AppContextProvider>
</Suspense>,
document.getElementById('root')
);
2 changes: 1 addition & 1 deletion src/client/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export function requestPvs(callback: Function): void {
.query<Ipvs>({
query: gql`
{
pvs
pvs(routerName: "allHouses")
}
`
})
Expand Down
5 changes: 5 additions & 0 deletions src/nodeuii/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,20 @@ import Koa from 'koa';
import serve from 'koa-static';
import cors from 'koa2-cors';
import log4js from 'log4js';
import koaBody from 'koa-body';

import ErrorHander from './middleware/ErrorHander';
import AnalysicsHander from './middleware/AnalysicsHander';
import controller from './controllers';
import config from './config';
import './controllers/schedule';



const app = new Koa();

app.use(koaBody());

// 错误日志记录
log4js.configure({
appenders: {
Expand Down
9 changes: 6 additions & 3 deletions src/nodeuii/controllers/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function initGraphQL(app: Koa): void {
type Query {
allHouses(year: Int): [House]
spiderPageOne: PageOneArray
pvs: Int
pvs(routerName: String): Int
}
`;

Expand All @@ -48,8 +48,11 @@ function initGraphQL(app: Koa): void {
return allHouses;
},
spiderPageOne: async () => spider.spiderPageOne(),
pvs: async (): Promise<number> => {
const analytics = await analyticsModel.find();
pvs: async (
_parent: never, // 不使用第一个变量
args: string
): Promise<number> => {
const analytics = await analyticsModel.find(args);
return analytics.length;
}
}
Expand Down
15 changes: 13 additions & 2 deletions src/nodeuii/middleware/AnalysicsHander.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,19 @@ const ErrorHander = {
init(app: Koa): void {
// 捕获 请求
app.use(async (ctx: Koa.Context, next: Function) => {
if (ctx.request.method !== 'OPTIONS') {
analyticsModel.add({ ip: ctx.request.ip });
if (ctx.method !== 'OPTIONS') {
// graphql 请求
if (ctx.request.url === '/graphql' && ctx.request.body.query) {
const queryString: string = ctx.request.body.query.replace(
/[\s|\n]/g,
''
);
const matchedArray = queryString.match(/(?<={)\w+/);
const routerName = matchedArray == null ? '' : matchedArray[0];
analyticsModel.add({ routerName });
} else {
analyticsModel.add({ routerName: ctx.request.path.substr(1) });
}
}
await next();
});
Expand Down
2 changes: 1 addition & 1 deletion src/nodeuii/middleware/ErrorHander.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const ErrorHander = {
// 捕获 404 错误
app.use(async (ctx: Koa.Context, next: Function) => {
await next();
if (ctx.status === 404) {
if (ctx.status === 404 && ctx.url !== '/404.html') {
ctx.redirect('/404.html');
}
});
Expand Down
6 changes: 3 additions & 3 deletions src/nodeuii/models/analyticsModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const mongoose = DbHelper.connect();

// 创建数据库
const analyticsSchema = new mongoose.Schema({
ip: String,
routerName: String,
createdTime: { type: Date, default: Date.now }
});
// 创建表
Expand All @@ -24,8 +24,8 @@ const analyticsModel = {
return item;
},

find() {
return AnalyticsCol.find({}, (err, analytics: cdFang.Ianalytics[]) => {
find(query: object) {
return AnalyticsCol.find(query, (err, analytics: cdFang.Ianalytics[]) => {
if (err) {
throw new Error(err);
}
Expand Down
4 changes: 4 additions & 0 deletions src/nodeuii/utils/dbHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ const DbHelper = {
console.warn('连接mongodb成功。');
}
);
// 单例模式
DbHelper.connect = () => {
return mongoose;
};
return mongoose;
}
};
Expand Down
2 changes: 1 addition & 1 deletion types/cdFang.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ declare namespace cdFang {
}

interface Ianalytics {
ip: string;
routerName: string;
createdTime?: Date;
}

Expand Down

0 comments on commit b5d1cb4

Please sign in to comment.