保誠-保戶業務員媒合平台
HelenHuang
2022-06-09 9bdb95c9e34cef640534e5e5a1e2225a80442000
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
'use strict'
 
/*
 * node-res
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/
 
const mime = require('mime-types')
const etag = require('etag')
const vary = require('vary')
const onFinished = require('on-finished')
const destroy = require('destroy')
 
const methods = require('./methods')
 
const returnContentAndType = function (body) {
  /**
   * Return the body and it's type when
   * body is a string.
   */
  if (typeof (body) === 'string') {
    return {
      body,
      type: /^\s*</.test(body) ? 'text/html' : 'text/plain'
    }
  }
 
  /**
   * If body is a buffer, return the exact copy
   * and type as bin.
   */
  if (Buffer.isBuffer(body)) {
    return { body, type: 'application/octet-stream' }
  }
 
  /**
   * If body is a number or boolean. Convert it to
   * a string and return the type as text.
   */
  if (typeof (body) === 'number' || typeof (body) === 'boolean') {
    return { body: String(body), type: 'text/plain' }
  }
 
  /**
   * Otherwise check whether body is an object or not. If yes
   * stringify it and otherwise return the exact copy.
   */
  return typeof (body) === 'object'
    ? { body: JSON.stringify(body), type: 'application/json' }
    : { body }
}
 
/**
 * A simple IO module to make consistent HTTP response, without
 * worrying about underlying details.
 *
 * @module Response
 */
const Response = exports = module.exports = {}
 
/**
 * Copying all the descriptive methods to the response object.
 */
Response.descriptiveMethods = Object.keys(methods).map((method) => {
  Response[method] = function (req, res, body) {
    Response.status(res, methods[method])
    Response.send(req, res, body)
  }
  return method
})
 
/**
 * Returns the value of an existing header on
 * the response object
 *
 * @method getHeader
 *
 * @param  {ServerResponse}  res
 * @param  {String}  key
 *
 * @return {Array|String} Return type depends upon the header existing value
 *
 * @example
 * ```js
 * nodeRes.getHeader(res, 'Content-type')
 * ```
 */
Response.getHeader = function (res, key) {
  return res.getHeader(key)
}
 
/**
 * Sets header on the response object. This method will wipe off
 * existing values. To append to existing values, use `append`.
 *
 * @method header
 *
 * @param  {http.ServerResponse}         res
 * @param  {String}         key
 * @param  {String|Array}   value
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.header(res, 'Content-type', 'application/json')
 *
 * // or set an array of headers
 * nodeRes.header(res, 'Link', ['<http://localhost/>', '<http://localhost:3000/>'])
 * ```
 */
Response.header = function (res, key, value) {
  const values = Array.isArray(value) ? value.map(String) : value
  res.setHeader(key, values)
}
 
/**
 * Appends value to the header existing values.
 *
 * @method append
 *
 * @param  {http.ServerResponse}         res
 * @param  {String}         key
 * @param  {String|Array}   value
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.append(res, 'Content-type', 'application/json')
 *
 * // or append an array of headers
 * nodeRes.append(res, 'Link', ['<http://localhost/>', '<http://localhost:3000/>'])
 * ```
 */
Response.append = function (res, key, value) {
  const previousValue = Response.getHeader(res, key)
 
  const headers = previousValue
    ? (Array.isArray(previousValue) ? previousValue.concat(value) : [previousValue].concat(value))
    : value
 
  Response.header(res, key, headers)
}
 
/**
 * Set status on the HTTP res object
 *
 * @method status
 *
 * @param  {http.ServerResponse} res
 * @param  {Number} code
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.status(res, 200)
 * ```
 */
Response.status = function (res, code) {
  res.statusCode = code
}
 
/**
 * Sets the header on response object, only if it
 * does not exists.
 *
 * @method safeHeader
 *
 * @param  {http.ServerResponse}   res
 * @param  {String}                key
 * @param  {String|Array}          value
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.safeHeader(res, 'Content-type', 'application/json')
 * ```
 */
Response.safeHeader = function (res, key, value) {
  if (!res.getHeader(key)) {
    Response.header(res, key, value)
  }
}
 
/**
 * Removes the header from response
 *
 * @method removeHeader
 *
 * @param  {http.ServerResponse}     res
 * @param  {String}                  key
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.removeHeader(res, 'Content-type')
 * ```
 */
Response.removeHeader = function (res, key) {
  res.removeHeader(key)
}
 
/**
 * Write string or buffer to the response object.
 *
 * @method write
 *
 * @param  {http.ServerResponse}  res
 * @param  {String|Buffer}        body
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.write(res, 'Hello world')
 * ```
 */
Response.write = function (res, body) {
  res.write(body)
}
 
/**
 * Explictly end HTTP response
 *
 * @method end
 *
 * @param  {http.ServerResponse}         res
 * @param  {String|Buffer}               [payload]
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.end(res, 'Hello world')
 * ```
 */
Response.end = function (res, payload) {
  res.end(payload)
}
 
/**
 * Send body as the HTTP response and end it. Also
 * this method will set the appropriate `Content-type`
 * and `Content-length`.
 *
 * If body is set to null, this method will end the response
 * as 204.
 *
 * @method send
 *
 * @param  {http.ServerRequest}             req
 * @param  {http.ServerResponse}            res
 * @param  {String|Buffer|Object|Stream}    body
 * @param  {Boolean}                        [generateEtag = true]
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.send(req, res, 'Hello world')
 *
 * // or html
 * nodeRes.send(req, res, '<h2> Hello world </h2>')
 *
 * // or JSON
 * nodeRes.send(req, res, { greeting: 'Hello world' })
 *
 * // or Buffer
 * nodeRes.send(req, res, Buffer.from('Hello world', 'utf-8'))
 *
 * // Ignore etag
 * nodeRes.send(req, res, 'Hello world', false)
 * ```
 */
Response.send = function (req, res, body = null, generateEtag = true) {
  /**
   * Handle streams
   */
  if (body && typeof (body.pipe) === 'function') {
    Response
      .stream(res, body)
      .catch((error) => {
        Response.status(res, error.code === 'ENOENT' ? 404 : 500)
        Response.send(req, res, error.message, generateEtag)
      })
    return
  }
 
  const chunk = Response.prepare(res, body)
 
  if (chunk === null || req.method === 'HEAD') {
    Response.end(res)
    return
  }
 
  /**
   * Generate etag when instructured for
   */
  if (generateEtag) {
    Response.etag(res, chunk)
  }
 
  Response.end(res, chunk)
}
 
/**
 * Sets the Etag header for a given body chunk
 *
 * @method etag
 *
 * @param  {http.ServerResponse}         res
 * @param  {String|Buffer}               body
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.etag(res, 'Hello world')
 * ```
 */
Response.etag = function (res, body) {
  Response.header(res, 'ETag', etag(body))
}
 
/**
 * Prepares the response body by encoding it properly. Also
 * sets appropriate headers based upon the body content type.
 *
 * This method is used internally by `send`, so you should
 * never use it when calling `send`.
 *
 * It is helpful when you want to get the final payload and end the
 * response at a later stage.
 *
 * @method prepare
 *
 * @param  {http.ServerResponse}  res
 * @param  {Mixed}                body
 *
 * @return {String}
 *
 * @example
 * ```js
 * const chunk = nodeRes.prepare(res, '<h2> Hello </h2>')
 *
 * if (chunk) {
 *   nodeRes.etag(res, chunk)
 *
 *   if (nodeReq.fresh(req, res)) {
 *     chunk = null
 *     nodeRes.status(304)
 *   }
 *
 *   nodeRes.end(chunk)
 * }
 * ```
 */
Response.prepare = function (res, body) {
  if (body === null) {
    Response.status(res, 204)
    Response.removeHeader(res, 'Content-Type')
    Response.removeHeader(res, 'Content-Length')
    Response.removeHeader(res, 'Transfer-Encoding')
    return null
  }
 
  let { body: chunk, type } = returnContentAndType(body)
 
  /**
   * Remove unwanted headers when statuscode is 204 or 304
   */
  if (res.statusCode === 204 || res.statusCode === 304) {
    Response.removeHeader(res, 'Content-Type')
    Response.removeHeader(res, 'Content-Length')
    Response.removeHeader(res, 'Transfer-Encoding')
    return chunk
  }
 
  const headers = typeof res.getHeaders === 'function' ? res.getHeaders() : (res._headers || {})
 
  /**
   * Setting content type. Ideally we can use `Response.type`, which
   * sets the right charset too. But we will be doing extra
   * processing for no reasons.
   */
  if (type && !headers['content-type']) {
    Response.header(res, 'Content-Type', `${type}; charset=utf-8`)
  }
 
  /**
   * setting up content length as response header
   */
  if (chunk && !headers['content-length']) {
    Response.header(res, 'Content-Length', Buffer.byteLength(chunk))
  }
 
  return chunk
}
 
/**
 * Prepares response for JSONP
 *
 * @method prepareJsonp
 *
 * @param  {http.ServerResponse}       res
 * @param  {Object}                    body
 * @param  {String}                    callbackFn
 *
 * @return {String}
 *
 * @example
 * ```js
 * const chunk = nodeRes.prepareJsonp(res, '<h2> Hello </h2>', 'callback')
 *
 * if (chunk) {
 *   nodeRes.etag(res, chunk)
 *
 *   if (nodeReq.fresh(req, res)) {
 *     chunk = null
 *     nodeRes.status(304)
 *   }
 *
 *   nodeRes.end(chunk)
 * }
 * ```
 */
Response.prepareJsonp = function (res, body, callbackFn) {
  Response.header(res, 'X-Content-Type-Options', 'nosniff')
  Response.safeHeader(res, 'Content-Type', 'text/javascript; charset=utf-8')
 
  const parsedBody = JSON
    .stringify(body)
    .replace(/\u2028/g, '\\u2028')
    .replace(/\u2029/g, '\\u2029')
 
  /**
   * setting up callbackFn on response body , typeof will make
   * sure not to throw error of client if callbackFn is not
   * a function
   */
  return '/**/ typeof ' + callbackFn + " === 'function' && " + callbackFn + '(' + parsedBody + ');'
}
 
/**
 * Returns the HTTP response with `Content-type`
 * set to `application/json`.
 *
 * @method json
 *
 * @param  {http.IncomingMessage}  req
 * @param  {http.ServerResponse}   res
 * @param  {Object}                body
 * @param  {Boolean}               [generateEtag = true]
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.json(req, res, { name: 'virk' })
 * nodeRes.json(req, res, [ 'virk', 'joe' ])
 * ```
 */
Response.json = function (req, res, body, generateEtag) {
  Response.safeHeader(res, 'Content-Type', 'application/json; charset=utf-8')
  Response.send(req, res, body, generateEtag)
}
 
/**
 * Make JSONP response with `Content-type` set to
 * `text/javascript`.
 *
 * @method jsonp
 *
 * @param  {http.IncomingMessage}   req
 * @param  {http.ServerResponse}    res
 * @param  {Object}                 body
 * @param  {String}                 [callbackFn = 'callback']
 * @param  {Boolean}                [generateEtag = true]
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.jsonp(req, res, { name: 'virk' }, 'callback')
 * ```
 */
Response.jsonp = function (req, res, body, callbackFn = 'callback', generateEtag) {
  Response.send(req, res, Response.prepareJsonp(res, body, callbackFn), generateEtag)
}
 
/**
 * Set `Location` header on the HTTP response.
 *
 * @method location
 *
 * @param  {http.ServerResponse} res
 * @param  {String}              url
 *
 * @return {void}
 */
Response.location = function (res, url) {
  Response.header(res, 'Location', url)
}
 
/**
 * Redirect the HTTP request to the given url.
 *
 * @method redirect
 *
 * @param  {http.IncomingMessage} req
 * @param  {http.ServerResponse}  res
 * @param  {String}               url
 * @param  {Number}              [status = 302]
 *
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.redirect(req, res, '/')
 * ```
 */
Response.redirect = function (req, res, url, status = 302) {
  const body = ''
  Response.status(res, status)
  Response.location(res, url)
  Response.send(req, res, body)
}
 
/**
 * Add vary header to the HTTP response.
 *
 * @method vary
 *
 * @param  {http.ServerResponse} res
 * @param  {String}              field
 *
 * @return {void}
 */
Response.vary = function (res, field) {
  vary(res, field)
}
 
/**
 * Set content type header by looking up the actual
 * type and setting charset to utf8.
 *
 * ### Note
 * When defining custom charset, you must set pass the complete
 * content type, otherwise `false` will be set as the
 * content-type header.
 *
 * @method type
 *
 * @param  {http.IncomingMessage} req
 * @param  {http.ServerResponse}  res
 * @param  {String}              [charset]
 * @return {void}
 *
 * @example
 * ```js
 * nodeRes.type(res, 'html')
 *
 * nodeRes.type(res, 'json')
 *
 * nodeRes.type(res, 'text/html', 'ascii')
 * ```
 */
Response.type = function (res, type, charset) {
  type = charset ? `${type}; charset=${charset}` : type
  Response.safeHeader(res, 'Content-Type', mime.contentType(type))
}
 
/**
 * Pipe stream to the response. Also this method will make sure
 * to destroy the stream, if request gets cancelled.
 *
 * The promise resolve when response finishes and rejects, when
 * stream raises errors.
 *
 * @method stream
 *
 * @param {Object} res
 * @param {Stream} body
 *
 * @returns {Promise}
 *
 * @example
 * ```js
 * Response.stream(res, fs.createReadStream('foo.txt'))
 *
 * // handle stream errors
 * Response
 *   .stream(res, fs.createReadStream('foo.txt'))
 *   .catch((error) => {
 *   })
 * ```
 */
Response.stream = function (res, body) {
  return new Promise((resolve, reject) => {
    if (typeof (body.pipe) !== 'function') {
      reject(new Error('Body is not a valid stream'))
      return
    }
 
    let finished = false
 
    /**
     * Error in stream
     */
    body.on('error', (error) => {
      if (finished) {
        return
      }
 
      finished = true
      destroy(body)
 
      reject(error)
    })
 
    /**
     * Consumed stream
     */
    body.on('end', resolve)
 
    /**
     * Written response
     */
    onFinished(res, function () {
      finished = true
      destroy(body)
    })
 
    /**
     * Pipe to res
     */
    body.pipe(res)
  })
}