Skip to content

Commit 38a9c98

Browse files
committed
refactor(server): update to koa2
1 parent 3c7f5d4 commit 38a9c98

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+3670
-4299
lines changed

.eslintrc.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ module.exports = {
44
"parser": "babel-eslint",
55
"env": {
66
"browser": true,
7-
"mocha": true
7+
"jest": true,
8+
"node": true
89
},
910
"plugins": [
1011
"html"

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<p align="center"><a href="https://easy-mock.com" target="_blank"><img width="100"src="http://img.souche.com/20170509/png/fff9d8506199c4bf8cc53bad9d849215.png"></a></p>
22

33
<p align="center">
4-
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/node-%3E%3D7.4.0-green.svg?style=flat" alt="Node.js Version"></a>
4+
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/node-%3E%3D8.9.1-green.svg?style=flat" alt="Node.js Version"></a>
55
<a href="https://www.mongodb.com"><img src="https://img.shields.io/badge/mongo-%3E%3D3.4.1-green.svg?style=flat" alt="MongoDB Version"></a>
66
<a href="https://circleci.com/gh/easy-mock/easy-mock/tree/dev"><img src="https://img.shields.io/circleci/project/easy-mock/easy-mock/dev.svg" alt="Build Status"></a>
77
<a href="https://codecov.io/github/easy-mock/easy-mock?branch=dev"><img src="https://img.shields.io/codecov/c/github/easy-mock/easy-mock/dev.svg" alt="Coverage Status"></a>
@@ -58,7 +58,7 @@ visualization view.
5858
## Quick Start
5959

6060
> Before starting, we assume that you're already have installed
61-
> [Node.js](https://nodejs.org) (>= v7.4) and [MongoDB](https://www.mongodb.com)
61+
> [Node.js](https://nodejs.org) (>= v8.9) and [MongoDB](https://www.mongodb.com)
6262
> (>= v3.4).
6363
6464
### Installation

README.zh-CN.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<p align="center"><a href="https://easy-mock.com" target="_blank"><img width="100"src="http://img.souche.com/20170509/png/fff9d8506199c4bf8cc53bad9d849215.png"></a></p>
22

33
<p align="center">
4-
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/node-%3E%3D7.4.0-green.svg?style=flat" alt="Node.js Version"></a>
4+
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/node-%3E%3D8.9.1-green.svg?style=flat" alt="Node.js Version"></a>
55
<a href="https://www.mongodb.com"><img src="https://img.shields.io/badge/mongo-%3E%3D3.4.1-green.svg?style=flat" alt="MongoDB Version"></a>
66
<a href="https://circleci.com/gh/easy-mock/easy-mock/tree/dev"><img src="https://img.shields.io/circleci/project/easy-mock/easy-mock/dev.svg" alt="Build Status"></a>
77
<a href="https://codecov.io/github/easy-mock/easy-mock?branch=dev"><img src="https://img.shields.io/codecov/c/github/easy-mock/easy-mock/dev.svg" alt="Coverage Status"></a>
@@ -53,7 +53,7 @@ Easy Mock 是一个可视化,并且能快速生成**模拟数据**的持久化
5353

5454
## 快速开始
5555

56-
> 在开始之前,假设你已经成功安装了 [Node.js](https://nodejs.org)**v7.4** 以上)和 [MongoDB](https://www.mongodb.com)**v3.4** 以上)。
56+
> 在开始之前,假设你已经成功安装了 [Node.js](https://nodejs.org)**v8.9** 以上)和 [MongoDB](https://www.mongodb.com)**v3.4** 以上)。
5757
5858
### 安装
5959

app.js

+37-58
Original file line numberDiff line numberDiff line change
@@ -1,85 +1,64 @@
11
'use strict'
22

3-
const _ = require('lodash')
4-
const koa = require('koa')
3+
const Koa = require('koa')
54
const path = require('path')
6-
const cors = require('koa-cors')
75
const config = require('config')
8-
const error = require('koa-error')
6+
const koaJwt = require('koa-jwt')
7+
const cors = require('@koa/cors')
8+
const koaBody = require('koa-body')
9+
const onerror = require('koa-onerror')
910
const favicon = require('koa-favicon')
1011
const validate = require('koa-validate')
11-
const jwtMongo = require('koa-jwt-mongo')
12-
const bodyParser = require('koa-bodyparser')
13-
const pathToRegexp = require('path-to-regexp')
1412
const staticCache = require('koa-static-cache')
15-
const koaBunyanLogger = require('koa-bunyan-logger')
1613

1714
const util = require('./util')
18-
const logger = require('./util/log')
15+
const logger = require('./util/logger')
1916
const middleware = require('./middlewares')
2017
const routerConfig = require('./router-config')
2118

22-
const app = module.exports = koa()
23-
const resolve = file => path.resolve(__dirname, file)
24-
const isProd = process.env.NODE_ENV === 'production'
25-
26-
const serve = (pf, filePath, cache) => staticCache(resolve(filePath), {
27-
prefix: pf,
28-
gzip: true,
29-
dynamic: true,
30-
maxAge: cache && isProd ? 60 * 60 * 24 * 30 : 0
31-
})
19+
const app = module.exports = new Koa()
20+
const uploadConf = config.get('upload')
21+
const jwtSecret = config.get('jwt.secret')
3222

3323
util.dropFileSchedule()
24+
onerror(app)
3425
validate(app)
3526

36-
const requestLogger = isProd
37-
? koaBunyanLogger.requestLogger()
38-
: function * (next) {
39-
yield next
40-
}
41-
42-
app.proxy = config.get('proxy')
4327
app
4428
.use(favicon(path.join(__dirname, '/public/images/icon.png')))
4529
.use(serve('/dist', './dist'))
4630
.use(serve('/public', './public'))
47-
.use(serve('/upload', path.resolve(__dirname, 'config', config.get('upload').dir)))
48-
.use(koaBunyanLogger(logger))
49-
.use(koaBunyanLogger.requestIdContext())
50-
.use(requestLogger)
51-
.use(cors({
52-
methods: 'GET,HEAD,PUT,POST,DELETE,PATCH',
53-
credentials: true,
54-
maxAge: 2592000
55-
}))
56-
.use(error())
57-
.use(bodyParser())
58-
.use(middleware.common)
59-
.use(middleware.error)
60-
.use(jwtMongo({
61-
uri: config.get('db'),
62-
jwtExp: config.get('jwt.expire'),
63-
collection: config.get('jwt.collection'),
64-
jwtOptions: {
65-
secret: config.get('jwt.secret'),
66-
key: config.get('jwt.key')
67-
},
68-
jwtUnless () {
69-
const path = this.path
70-
const prefix = `/${path.split('/')[1]}`
71-
return !(new RegExp(config.get('routerPrefix.api'))).test(prefix)
72-
? true : _.some(config.get('publicAPIs').map(
73-
o => pathToRegexp(o).test(this.path)
74-
), Boolean)
75-
}
31+
.use(serve('/upload', path.resolve(__dirname, 'config', uploadConf.dir)))
32+
.use(logger)
33+
.use(koaJwt({ secret: jwtSecret }).unless({
34+
path: [
35+
/^\/(public|dist|upload|mock)\//,
36+
'/api/u/login',
37+
'/api/u/register',
38+
'/api/mock/by_projects',
39+
'/api/mock/export',
40+
'/api/wallpaper'
41+
]
7642
}))
43+
.use(cors({ credentials: true, maxAge: 2592000 }))
44+
.use(koaBody({ multipart: true }))
45+
.use(middleware.util)
7746
.use(routerConfig.mock.routes())
7847
.use(routerConfig.mock.allowedMethods())
7948
.use(routerConfig.api.routes())
8049
.use(routerConfig.api.allowedMethods())
81-
.use(middleware.view(app))
50+
// .use(middleware.view(app))
51+
52+
app.proxy = config.get('proxy')
53+
54+
/* istanbul ignore if */
55+
if (!module.parent) app.listen(config.get('port'))
8256

83-
if (!module.parent) {
84-
app.listen(config.get('port'))
57+
function serve (prefix, filePath) {
58+
return staticCache(path.resolve(__dirname, filePath), {
59+
prefix: prefix,
60+
gzip: true,
61+
dynamic: true,
62+
maxAge: 60 * 60 * 24 * 30
63+
})
8564
}

circle.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
machine:
22
node:
3-
version: 7.4.0
3+
version: 8.9.1
44

55
test:
66
override:

config/default.json

-54
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,10 @@
11
{
22
"port": 7300,
33
"pageSize": 30,
4-
"routerPrefix": {
5-
"mock": "/mock",
6-
"api": "/api"
7-
},
84
"db": "",
95
"unsplashClientId": "",
10-
"gravatar": [
11-
"//img.souche.com/20161230/png/58f22ad636a0f33bad8762688f78d425.png",
12-
"//img.souche.com/20161230/png/6cdcda90c2f86ba1f45393cf5b26e324.png",
13-
"//img.souche.com/20161230/png/f9d10bb683d940dd14dc1b1344e89568.png",
14-
"//img.souche.com/20161230/png/8bb4f0fd45ed6ae26533eadd85f0f7ea.png",
15-
"//img.souche.com/20161230/png/0795744371fd5869af6cab796bdacb95.png",
16-
"//img.souche.com/20161230/png/bc836261fbb654dda6b653e428014279.png",
17-
"//img.souche.com/20161230/png/fd9f8aecab317e177655049a49b64d02.png"
18-
],
196
"jwt": {
20-
"key": "user",
217
"expire": "14 days",
22-
"collection": "tokens",
238
"secret": "shared-secret"
249
},
2510
"proxy": false,
@@ -32,45 +17,6 @@
3217
"day": -1
3318
}
3419
},
35-
"publicAPIs": [
36-
"/api/proxy",
37-
"/api/u/login",
38-
"/api/u/register",
39-
"/api/mock/by_projects",
40-
"/api/mock/export",
41-
"/api/wallpaper"
42-
],
43-
"mockExample": {
44-
"common": {
45-
"success": true,
46-
"data": [{
47-
"user": {
48-
"name": "演示用"
49-
}
50-
}]
51-
},
52-
"getFunction": "{ success :true, data: { default: \"hah\", _req: function({ _req }) { return _req }, name: function({ _req }) { return _req.query.name || this.default }}}",
53-
"postFunction": "{ data: { img: function({ _req, Mock }) { return _req.body.fileName + '_' + Mock.mock('@image') }}}",
54-
"random": {
55-
"success": true,
56-
"data": {
57-
"projects|3-10": [{
58-
"name": "演示用",
59-
"url": "@url",
60-
"email": "@email",
61-
"address": "@county(true)",
62-
"string|1-10": "",
63-
"number|1-100": 100,
64-
"boolean|1-2": true,
65-
"object|2": {
66-
"310000": "上海市",
67-
"320000": "江苏省",
68-
"330000": "浙江省"
69-
}
70-
}]
71-
}
72-
}
73-
},
7420
"fe": {
7521
"copyright": "",
7622
"storageNamespace": "easy-mock_",

controllers/dashboard.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
'use strict'
2+
3+
const moment = require('moment')
4+
const LRU = require('lru-cache')
5+
6+
const { Project, Mock, MockCount, User } = require('../models')
7+
8+
const cache = LRU({ max: 1, maxAge: 1000 * 60 * 60 })
9+
10+
/**
11+
* 获取 Mock 使用次数
12+
*/
13+
14+
function getUseTotalCount (query = {}) {
15+
return MockCount.aggregate(
16+
{ $match: query },
17+
{ $group: { _id: null, total: { $sum: '$count' } } }
18+
).then(data => data[0] ? /* istanbul ignore next */ data[0].total : 0)
19+
}
20+
21+
module.exports = class DashboardController {
22+
/**
23+
* 仪表板
24+
* @param Object ctx
25+
*/
26+
27+
static async list (ctx) {
28+
let result = cache.get('list')
29+
const query = {
30+
create_at: {
31+
'$gte': new Date(moment().format('YYYY-MM-DD'))
32+
}
33+
}
34+
35+
if (!result) {
36+
const data = await Promise.all([
37+
User.count(),
38+
Mock.count(),
39+
Project.count(),
40+
getUseTotalCount(),
41+
User.count(query),
42+
Mock.count(query),
43+
Project.count(query),
44+
getUseTotalCount(query)
45+
])
46+
47+
result = {
48+
total: {
49+
userCount: data[0],
50+
mockCount: data[1],
51+
projectCount: data[2],
52+
mockUseCount: data[3]
53+
},
54+
today: {
55+
userCount: data[4],
56+
mockCount: data[5],
57+
projectCount: data[6],
58+
mockUseCount: data[7]
59+
}
60+
}
61+
62+
cache.set('list', result)
63+
}
64+
65+
ctx.body = ctx.util.resuccess(result)
66+
}
67+
}

0 commit comments

Comments
 (0)