-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
112 lines (102 loc) · 2.59 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const fs = require('fs-extra');
const path = require('path');
const http = require('http');
const Koa = require('koa');
const cors = require('koa2-cors');
const serve = require('koa-static');
const koaBody = require('koa-body');
const Router = require('koa-router');
const favicon = require('koa-favicon');
const compress = require('koa-compress');
const sse = require('koa-sse-stream');
const PORT = 9999;
const models = require('./models');
const mock = require('./utils/mock');
const { formatQuery } = require('./utils/_');
const speed = require('./middlewares/speed');
const cookie = require('./middlewares/cookie');
const mime = require('./middlewares/mime');
const app = new Koa();
const server = http.createServer(app.callback());
const io = require('socket.io')(server);
const router = new Router();
io.on('connection', socket => {
socket.on('request', v => {
socket.emit('response', v);
});
});
router.post(
'/upload',
koaBody({
multipart: true,
patchKoa: true
}),
ctx => {
const { file } = ctx.request.files;
const { name = Date.now() } = ctx.request.body;
const filePath = path.join(__dirname, `.tmp/${name}`);
fs.ensureFileSync(filePath);
fs.createReadStream(file.path).pipe(fs.createWriteStream(filePath));
ctx.body = fs.createReadStream(file.path);
}
);
router.get('/blob/:file', ctx => {
const { file } = ctx.params;
const { type } = ctx.query;
const filePath = path.join(__dirname, `./blob/${file}`);
if (fs.existsSync(filePath)) {
if (type === 'chunked') {
ctx.body = fs.createReadStream(filePath);
} else {
ctx.body = fs.readFileSync(filePath);
}
} else {
ctx.body = `没有对应文件--${file}`;
}
});
router.get('/api/:cate', speed, ctx => {
const { cate } = ctx.params;
const { type, ...query } = formatQuery(ctx.query);
const model = models[cate];
if (model) {
ctx.body = mock(type, model, query);
} else {
ctx.status = 404;
ctx.body = `没有对应模型--${cate}`;
}
});
router.get('/setCookie', ctx => {
ctx.cookies.set('age', 18);
});
router.get('/sse', ctx => {
ctx.sse.send('a');
setTimeout(() => {
ctx.sse.send('b');
}, 1000);
setTimeout(() => {
ctx.sse.send('c');
}, 2000);
setTimeout(() => {
ctx.sse.sendEnd();
}, 3000);
});
app
.use(compress())
.use(
cors({
credentials: true,
maxAge: 60 * 60
})
)
.use(cookie)
.use(mime)
.use(favicon('favicon.jpg'))
.use(serve('public'))
.use(sse({
maxClients: 5000,
pingInterval: 30000
}))
.use(router.routes());
server.listen(PORT, function() {
console.log(`listen to ${PORT}`);
});