-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.ts
596 lines (524 loc) · 12.1 KB
/
index.ts
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
/**
* Copyright (c) 2018 Chan Zewail
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import getType from 'cache-content-type';
import contentDisposition from 'content-disposition';
import { OutgoingHttpHeaders, ServerResponse } from 'http';
import { extname } from 'path';
import compressible from 'compressible';
import { Container } from '../container';
import { Cookie } from '../cookie';
import { Application } from '../foundation/application';
import { Request } from '../request';
import { Resource } from '../resource/resource';
import { View } from '../view';
import { ViewFactory } from '../view/factory';
import { Statusable } from './statusable';
import { Stream } from 'stream';
import * as zlib from 'zlib';
const encodingMethods = {
gzip: zlib.createGzip,
deflate: zlib.createDeflate
};
// import statuses from 'statuses'
// import { IllegalArgumentError } from '../errors/illegal-argument-error'
const defaultContentTypes = {
JSON: 'application/json; charset=utf-8',
PLAIN: 'text/plain; charset=utf-8',
OCTET: 'application/octet-stream'
};
export class Response extends Statusable {
/**
* application
*/
protected app: Application = Container.get('app')
/**
* response statusCode
*/
protected _code: number;
/**
* response Header
*/
protected _header: OutgoingHttpHeaders;
/**
* response data
*/
protected _data: any;
/**
* response cookies
*/
protected cookies: Cookie[] = [];
/**
* patched methods
*/
// [key: string]: any;
constructor(data?: any, code = 200, header: OutgoingHttpHeaders = {}) {
super();
/**
* status code
* @type
*/
this._code = code;
/**
* http headers
* @type
*/
this._header = this.parseHeaders(header);
/**
* init data
*/
this.setData(data);
}
/**
* code setter
*/
set code(code) {
this.setCode(code);
}
/**
* code getter
*/
get code() {
return this._code;
}
/**
* data setter
*/
set data(data) {
this.setData(data);
}
/**
* data getter
*/
get data() {
return this._data;
}
/**
* parse init headers
* @param headers
*/
private parseHeaders(headers: OutgoingHttpHeaders) {
const keys = Object.keys(headers);
const _headers: OutgoingHttpHeaders = {};
for (const key of keys) {
_headers[key.toLocaleLowerCase()] = headers[key];
}
return _headers;
}
/**
* throw http exception with code and message
* @param message exception message
* @param code exception code
*/
error(message: any, code = 404) {
this.setCode(code);
this.setData(message);
return this;
}
/**
* set success data in ctx.body
* @param data data
* @param code http code
*/
success(data: any, code = 200) {
this.setCode(code);
this.setData(data);
return this;
}
/**
* get http header
*/
getHeader(name: string) {
return this._header[name.toLowerCase()];
}
/**
* Set response header
* The original response headers are merged when the name is passed in as object
*
* @param name Response header parameter name
* @param value Response header parameter value
*/
setHeader(name: any, value: any) {
this._header[name.toLowerCase()] = value;
return this;
}
/**
* remove header from response
* @param name
*/
removeHeader(name: any) {
delete this._header[name.toLowerCase()];
return this;
}
/**
* getHeader alias
* @public
*/
getHeaders() {
return this._header;
}
/**
* setHeader alias
* @public
*/
setHeaders(headers: any) {
const keys = Object.keys(headers);
for (const key of keys) {
this.setHeader(key.toLowerCase(), headers[key]);
}
return this;
}
/**
* get http code
* @public
*/
getCode() {
return this.code;
}
/**
* getCode alias
* @public
*/
getStatus() {
return this.getCode();
}
/**
* set code
* @public
* @param code status
*/
setCode(code = 200) {
if (code) this._code = code;
return this;
}
/**
* setCode alias
* @public
* @param code status
*/
setStatus(code: number) {
return this.setCode(code);
}
/**
* get return data
* @public
*/
getData() {
return this._data;
}
/**
* set content-type
* @param type
*/
setType(type: string) {
const _type = getType(type);
if (_type) {
this.setHeader('Content-Type', _type);
}
return this;
}
/**
* get content type
*/
getType() {
const type = this.getHeader('Content-Type') as string;
if (!type) return '';
return type.split(';', 1)[0];
}
/**
* set length header
* @param length
*/
setLength(length: number) {
this.setHeader('Content-Length', length);
return this;
}
/**
* get response data length
*/
getLength() {
const length = this.getHeader('Content-Length') as string;
return length ? parseInt(length, 10) : 0;
}
/**
* set vary header
* @param field
*/
setVary(field: string) {
const varyHeader = this.getHeader('Vary') || '';
const varys = String(varyHeader).split(',');
varys.push(field);
this.setHeader('Vary', varys.filter((v: string) => !!v).join(','));
}
/**
* LastModified
* @public
* @param time time
* @returns this
*/
lastModified(time: string | Date | number) {
if (time instanceof Date) {
this.setHeader('Last-Modified', time.toUTCString());
return this;
}
if (typeof time === 'string' || typeof time === 'number') {
this.setHeader('Last-Modified', (new Date(time)).toUTCString());
return this;
}
return this;
}
/**
* Expires
* @param time time
*/
expires(time: string) {
this.setHeader('Expires', time);
return this;
}
/**
* ETag
* @param eTag eTag
*/
eTag(eTag: string) {
if (!/^(W\/)?"/.test(eTag)) {
this.setHeader('ETag', `"${eTag}"`);
return this;
}
this.setHeader('ETag', eTag);
return this;
}
/**
* CacheControl
* @param cache cache setting
*/
cacheControl(cache: string) {
this.setHeader('Cache-Control', cache);
return this;
}
/**
* Set the page to do no caching
* @public
*/
noCache() {
this.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
this.setHeader('Pragma', 'no-cache');
return this;
}
/**
* ContentType
* @public
* @param contentType The output type
* @param charset The output of language
*/
contentType(contentType: string, charset = 'utf-8') {
this.setHeader('Content-Type', `${contentType}; charset=${charset}`);
return this;
}
/**
* Contents-dispositions are set as "attachments" to indicate that the client prompts to download.
* Optionally, specify the filename to be downloaded.
* @public
* @param filename
* @returns this
*/
attachment(filename = '', options: any) {
if (filename) this.setType(extname(filename));
this.setHeader('Content-Disposition', contentDisposition(filename, options));
return this;
}
/**
* attachment alias
* @public
* @param filename
*/
download(data: any, filename = '', options: any) {
return this.setData(data).attachment(filename, options);
}
/**
* handle Resource data
*/
transformData(request: any) {
const data = this.getData();
if (!data) return data;
if (data instanceof Resource) {
return data.output();
}
if (data instanceof View) {
this.setType('html');
return (new ViewFactory(data)).output(request);
}
return data;
}
/**
* response with cookie instance
* @param _cookie
*/
withCookie(_cookie: any) {
if (_cookie instanceof Cookie) {
this.cookies.push(_cookie);
}
return this;
}
/**
* response with cookie
* @param key
* @param value
* @param options
*/
cookie(key: string, value: any, options: any = {}) {
this.withCookie(new Cookie(key, value, options));
return this;
}
/**
* set json response type
*/
json(data?: any) {
this.setType('json');
if (data) this.setData(data);
return this;
}
/**
* set html response type
*/
html(data?: any) {
this.setType('html');
if (data) this.setData(data);
return this;
}
/**
* set html response type
*/
text(data?: any) {
this.setType('text');
if (data) this.setData(data);
return this;
}
async commitCookies(request: any) {
for (const _cookie of this.cookies) {
request.cookies.set(_cookie.getName(), _cookie.getValue(), _cookie.getOptions());
}
if (this.app.needsSession) {
await request.session().autoCommit();
}
}
/**
* send headers
* @param res
*/
sendHeaders(res: ServerResponse) {
if (res.headersSent) return this;
const code = this.getCode();
const headers = this.getHeaders();
res.writeHead(code, headers);
return this;
}
/**
* Set the returned data
* @public
* @param data Returned data
*/
setData(data: any) {
this._data = data;
return this;
}
/**
* prepare response
* @param request
*/
prepare(request: Request) {
const data = this.transformData(request);
const shouldSetType = !this.getHeader('content-type');
// if no content
if (data === null || typeof data === 'undefined') {
this.setCode(204);
this.removeHeader('content-type');
this.removeHeader('content-length');
this.removeHeader('transfer-encoding');
return data || '';
}
// string
if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
if (shouldSetType) this.setHeader('content-type', defaultContentTypes.PLAIN);
this.setHeader('content-length', Buffer.byteLength(data.toString()));
return data.toString();
}
// buffer
if (Buffer.isBuffer(data)) {
if (shouldSetType) this.setHeader('content-type', defaultContentTypes.OCTET);
this.setHeader('content-length', data.length);
return data;
}
// stream
if (typeof data.pipe === 'function') {
this.removeHeader('content-length');
if (shouldSetType) this.setHeader('content-type', defaultContentTypes.OCTET);
return data;
}
// json
this.removeHeader('content-length');
if (shouldSetType) this.setHeader('content-type', defaultContentTypes.JSON);
return data;
}
/**
* send data
* @param request
* @public
*/
async send(request: Request) {
const data = this.prepare(request);
if (this.app.get('config').get('app.compress')) {
return this.endWithCompress(request, data);
}
return this.end(request, data);
}
/**
* end response
* @param request
* @param data
*/
async end(request: Request, data: any) {
const { res } = request;
// commit cookies
await this.commitCookies(request);
// responses
if (typeof data === 'string' || Buffer.isBuffer(data)) {
this.sendHeaders(res);
return res.end(data);
}
if (data instanceof Stream) {
this.sendHeaders(res);
return data.pipe(res);
};
// json
const jsonData = JSON.stringify(data);
if (!res.headersSent) {
this.setHeader('content-length', Buffer.byteLength(jsonData));
}
this.sendHeaders(res);
return res.end(jsonData);
}
/**
* end with compress
* @param request
*/
endWithCompress(request: Request, data: any) {
// if compress is disable
const encoding: string | false = request.acceptsEncodings('gzip', 'deflate', 'identity');
if (!encoding || encoding === 'identity') return this.end(request, data);
if (!compressible(this.getType())) return this.end(request, data);
const threshold = this.app.get('config').get('app.threshold', 1024);
if (threshold > this.getLength()) return this.end(request, data);
this.setHeader('Content-Encoding', encoding);
this.removeHeader('Content-Length');
const stream = encodingMethods[encoding as 'gzip' | 'deflate']({});
if (data instanceof Stream) {
data.pipe(stream);
} else {
stream.end(data);
}
return this.end(request, stream);
}
}