-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbootstrap.js
More file actions
246 lines (216 loc) · 6.23 KB
/
bootstrap.js
File metadata and controls
246 lines (216 loc) · 6.23 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
'use strict';
const { debug } = require('@axiosleo/cli-tool');
const { _foreach, _sleep } = require('@axiosleo/cli-tool/src/helper/cmd');
const { success, result, failed } = require('../src/response');
const multer = require('@koa/multer');
const { KoaApplication, Router, Model } = require('..');
if (require.main === module) {
const handle = async (context) => {
success({
body: context.koa.request.body,
query: context.koa.request.query,
params: context.params,
method: context.method
});
};
const root = new Router(null, {
middlewares: [async (context) => {
debug.log(`[${context.app_id}] ${context.method}: ${context.router.pathinfo}`);
}],
afters: [async (context) => {
debug.log(context.response);
}]
});
// default
root.push('any', '/***', async (context) => {
context.koa.body = 'hello, world!';
});
root.push('get', '/', async (context) => {
success('hello, world!');
});
// return NotFound response when not set method
root.push('', '/invalid', async (context) => {
context.koa.body = 'cannot be here, will return NotFound response';
});
// set multi-method
root.push('get|post', '/multi', async (context) => {
success({ method: context.method });
});
// path params
root.push('get', '/a/{:a}/b/{:b}', handle);
// any method
root.push('any', '/any', handle);
// some error
root.push('any', '/error', async () => {
throw new Error('error');
});
// send res by failed() method
root.push('any', '/failed', async () => {
failed({ data: 'something' }, '403;Unauthorized', 403);
});
// send res by result() method
root.push('any', '/result', async () => {
result(JSON.stringify({ hello: 'world!' }), 200, {
'Content-Type': 'application/json'
});
});
// send object res by result() method
root.get('/result/obj', async () => {
result([{ test: 123 }]);
});
// send res by success() method
root.push('any', '/success', async () => {
success('Hello, World!');
});
// send html content
root.push('any', '/html', async () => {
result('hello, world!', 200, {
'Content-Type': 'text/html'
});
});
// use model
root.push('any', '/model', async () => {
const model = new Model({
submodel: new Model({
submodel: new Model({
a: 'A'
})
})
});
success({
obj: model.toObj(),
json: model.toJson(),
properties: model.properties(),
count: model.count(),
});
});
// throw error by model
root.push('any', '/model/error', async () => {
Model.create({}, { param: 'required' });
});
// validate request
root.push('any', '/validate/{:param1}/{:param2}', async (context) => {
success({
result: 'all params is valid',
params: context.params,
query: context.query,
body: context.body
});
}, {
params: {
rules: {
param1: 'required',
param2: 'required'
}
},
query: {
rules: {
a: 'required',
b: 'integer'
}
},
body: {
rules: {
bodyA: 'required',
bodyB: 'integer'
},
messages: {
'required': 'The :attribute field is required......'
}
}
});
root.post('/upload', async (context) => {
// Array of files
const upload = multer();
const func = upload.any();
await func(context.koa, async () => { });
// read FormData
debug.log({
files: context.koa.request.files,
});
const file = context.koa.request.files[0];
context.koa.set('content-type', file.mimetype);
context.koa.body = file.buffer;
context.koa.attachment(file.originalname);
});
root.post('/upload/single', async (context) => {
// Single file
try {
const upload = multer();
const func = upload.single('file');
await func(context.koa, async () => { });
const file = context.koa.request.file;
debug.log({
files: context.koa.request.files,
file: context.koa.request.file,
});
context.koa.set('content-type', file.mimetype);
context.koa.body = file.buffer;
context.koa.attachment(file.originalname);
} catch (err) {
if (err.code === 'LIMIT_UNEXPECTED_FILE') {
failed({ data: 'must be a single file', field: err.field }, '400;Bad Request', 400);
}
}
});
root.post('/upload/fields', async (context) => {
try {
// Multiple files
const upload = multer();
const func = upload.fields([{ name: 'file', maxCount: 1 }, { name: 'file2', maxCount: 2 }]);
await func(context.koa, async () => { });
const file = context.koa.request.files.file[0];
const file2 = context.koa.request.files.file2[0];
debug.log({
file1: file,
file2
});
context.koa.set('content-type', file.mimetype);
context.koa.body = file.buffer;
context.koa.attachment(file.originalname);
} catch (err) {
debug.log(err);
if (err.code === 'LIMIT_UNEXPECTED_FILE') {
failed({ data: 'must be a multiple files', field: err.field }, '400;Bad Request', 400);
}
}
});
root.get('/session', async (context) => {
context.koa.session.test = { a: 'A' };
context.koa.session.save();
context.koa.redirect('/redirect');
});
root.get('/redirect', async (context) => {
const data = JSON.stringify({
session: context.koa.session.test,
});
success(data);
});
const test = async (context) => {
const arr = new Array(100).fill('');
await _foreach(arr, async (item, index) => {
context.koa.sse.send({ data: { item, index } });
await _sleep(1000);
});
context.koa.sse.end();
};
const { KoaSSEMiddleware } = require('../index').middlewares;
root.any('/sse', async (context) => {
const func = KoaSSEMiddleware();
await func(context.koa, async () => { });
context.koa.sse.send({ data: 'hello, world!' });
process.nextTick(test, context);
});
root.push('get', '/append', async (context) => {
for (let i = 0; i < 100; i++) {
await _sleep(100);
// context.koa.body += `hello, world! ${i}\n`;
// writer.write(`hello, world! ${i}\n`);
}
});
const app = new KoaApplication({
debug: true,
routers: [root]
});
app.start();
}