Skip to content

Commit a903edf

Browse files
committed
feat(server): use redis
1 parent e435b9f commit a903edf

File tree

15 files changed

+232
-167
lines changed

15 files changed

+232
-167
lines changed

app.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,18 @@ const app = module.exports = new Koa()
2121
const uploadConf = config.get('upload')
2222
const jwtSecret = config.get('jwt.secret')
2323

24-
util.dropFileSchedule()
24+
util.init()
2525
onerror(app)
2626
validate(app)
2727

2828
app
29-
.use(middleware.util)
3029
.use(middleware.ipFilter)
3130
.use(favicon(path.join(__dirname, '/public/images/icon.png')))
3231
.use(serve('/dist', './dist'))
3332
.use(serve('/public', './public'))
3433
.use(serve('/upload', path.resolve(__dirname, 'config', uploadConf.dir)))
3534
.use(logger)
35+
.use(middleware.util)
3636
.use(cors({ credentials: true, maxAge: 2592000 }))
3737
.use(koaJwt({ secret: jwtSecret }).unless((ctx) => {
3838
if (/^\/api/.test(ctx.path)) {

build/ci.sh

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
set -e
2-
echo '{"blackList": { "projects": ["222222222233333333331212"], "ips": ["127.0.0.1"] }}' > ./config/test.json
32
npm run lint
43
npm test
54

controllers/mock.js

+16-6
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@ const pathToRegexp = require('path-to-regexp')
1111

1212
const util = require('../util')
1313
const ft = require('../models/fields_table')
14-
const { MockProxy, ProjectProxy, MockCountProxy, UserGroupProxy } = require('../proxy')
14+
const { MockProxy, ProjectProxy, UserGroupProxy } = require('../proxy')
1515

16+
const redis = util.getRedis()
1617
const defPageSize = config.get('pageSize')
1718

1819
async function checkByMockId (mockId, uid) {
@@ -89,6 +90,7 @@ module.exports = class MockController {
8990
mode
9091
})
9192

93+
await redis.del('project:' + projectId)
9294
ctx.body = ctx.util.resuccess()
9395
}
9496

@@ -192,7 +194,7 @@ module.exports = class MockController {
192194
}
193195

194196
await MockProxy.updateById(api)
195-
197+
await redis.del('project:' + project.id)
196198
ctx.body = ctx.util.resuccess()
197199
}
198200

@@ -206,9 +208,17 @@ module.exports = class MockController {
206208
const method = ctx.method.toLowerCase()
207209
const jsonpCallback = query.jsonp_param_name && (query[query.jsonp_param_name] || 'callback')
208210
let { projectId, projectURL, mockURL } = ctx.pathNode
211+
const redisKey = 'project:' + projectId
209212
let apiData, apis, api
210213

211-
apis = await MockProxy.find({ project: projectId, method })
214+
apis = await redis.get(redisKey)
215+
216+
if (apis) {
217+
apis = JSON.parse(apis)
218+
} else {
219+
apis = await MockProxy.find({ project: projectId })
220+
if (apis[0]) await redis.set(redisKey, JSON.stringify(apis), 'EX', 60 * 30)
221+
}
212222

213223
if (apis[0] && apis[0].project.url === '/') {
214224
mockURL = projectURL
@@ -217,7 +227,7 @@ module.exports = class MockController {
217227

218228
api = apis.filter((item) => {
219229
const url = item.url.replace(/{/g, ':').replace(/}/g, '') // /api/{user}/{id} => /api/:user/:id
220-
return pathToRegexp(url).test(mockURL)
230+
return item.method === method && pathToRegexp(url).test(mockURL)
221231
})[0]
222232

223233
if (!api) ctx.throw(404)
@@ -285,7 +295,7 @@ module.exports = class MockController {
285295
}
286296
}
287297

288-
await MockCountProxy.newAndSave(api.id)
298+
await redis.lpush('mock.count', api._id)
289299
if (jsonpCallback) {
290300
ctx.type = 'text/javascript'
291301
ctx.body = `${jsonpCallback}(${JSON.stringify(apiData, null, 2)})`
@@ -414,7 +424,7 @@ module.exports = class MockController {
414424
})
415425

416426
await MockProxy.delByIds(ids)
417-
427+
await redis.del('project:' + projectId)
418428
ctx.body = ctx.util.resuccess()
419429
}
420430
}

controllers/project.js

+5
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
const _ = require('lodash')
44
const config = require('config')
55

6+
const util = require('../util')
67
const ft = require('../models/fields_table')
78
const SwaggerUtil = require('../util/swagger')
89
const { MockProxy, ProjectProxy, UserProjectProxy, UserGroupProxy } = require('../proxy')
910

11+
const redis = util.getRedis()
1012
const defPageSize = config.get('pageSize')
1113

1214
async function checkByProjectId (projectId, uid, creater) {
@@ -356,6 +358,7 @@ module.exports = class ProjectController {
356358
}
357359

358360
await ProjectProxy.updateById(project)
361+
await redis.del('project:' + id)
359362
ctx.body = ctx.util.resuccess()
360363
}
361364

@@ -386,6 +389,7 @@ module.exports = class ProjectController {
386389
}
387390

388391
await SwaggerUtil.create(project)
392+
await redis.del('project:' + id)
389393
ctx.body = ctx.util.resuccess()
390394
}
391395

@@ -411,6 +415,7 @@ module.exports = class ProjectController {
411415
}
412416

413417
await ProjectProxy.delById(id)
418+
await redis.del('project:' + id)
414419
ctx.body = ctx.util.resuccess()
415420
}
416421
}

controllers/util.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,9 @@ module.exports = class UtilController {
8585

8686
ctx.body = ctx.util.resuccess({
8787
path: new URL(path.join('upload', date, fileName), origin).href,
88-
expire: expireDay > 0 /* istanbul ignore next */
88+
expire: expireDay > 0
8989
? moment().add(expireDay, 'days').format('YYYY-MM-DD 00:00:00')
90-
: -1
90+
: /* istanbul ignore next */ -1
9191
})
9292
}
9393
}

middlewares/index.js

+29-29
Original file line numberDiff line numberDiff line change
@@ -7,43 +7,43 @@ const pathToRegexp = require('path-to-regexp')
77
const blackProjects = config.get('blackList.projects')
88
const blackIPs = config.get('blackList.ips')
99

10-
module.exports = class Middleware {
11-
static util (ctx, next) {
12-
const codeMap = {
13-
'-1': 'fail',
14-
'200': 'success',
15-
'401': 'token expired',
16-
'500': 'server error',
17-
'10001': 'params error'
18-
}
19-
20-
ctx.set('X-Request-Id', ctx.req.id)
10+
const codeMap = {
11+
'-1': 'fail',
12+
'200': 'success',
13+
'401': 'token expired',
14+
'500': 'server error',
15+
'10001': 'params error'
16+
}
2117

22-
ctx.util = {
23-
resuccess (data) {
24-
return {
25-
code: 200,
26-
success: true,
27-
message: codeMap['200'],
28-
data: data || null
29-
}
30-
},
31-
refail (message, code, data) {
32-
return {
33-
code: code || -1,
34-
success: false,
35-
message: message || codeMap[code],
36-
data: data || null
37-
}
38-
}
18+
const utilFn = {
19+
resuccess (data) {
20+
return {
21+
code: 200,
22+
success: true,
23+
message: codeMap['200'],
24+
data: data || null
3925
}
26+
},
27+
refail (message, code, data) {
28+
return {
29+
code: code || -1,
30+
success: false,
31+
message: message || codeMap[code],
32+
data: data || null
33+
}
34+
}
35+
}
4036

37+
module.exports = class Middleware {
38+
static util (ctx, next) {
39+
ctx.set('X-Request-Id', ctx.req.id)
40+
ctx.util = utilFn
4141
return next()
4242
}
4343

4444
static ipFilter (ctx, next) {
4545
if (ipFilter(ctx.ip, blackIPs, {strict: false})) {
46-
ctx.body = ctx.util.refail('请求频率太快,已被限制访问')
46+
ctx.body = utilFn.refail('请求频率太快,已被限制访问')
4747
return
4848
}
4949
return next()

0 commit comments

Comments
 (0)