1 | 'use strict';
|
2 |
|
3 | const REQUIRED_PROPERTIES = [
|
4 | 'url',
|
5 | 'body',
|
6 | 'statusCode',
|
7 | 'headers',
|
8 | 'elapsedTime'
|
9 | ];
|
10 |
|
11 | class Response {
|
12 | constructor() {
|
13 | this.headers = {};
|
14 | this.elapsedTime = 0;
|
15 | this.url;
|
16 | this.statusCode;
|
17 | this.body;
|
18 | this.httpResponse;
|
19 | }
|
20 |
|
21 | getHeader(header) {
|
22 | return this.headers[header];
|
23 | }
|
24 |
|
25 | addHeader(name, value) {
|
26 | if (typeof name === 'object') {
|
27 | for (const k in name) {
|
28 | this.addHeader(k, name[k]);
|
29 | }
|
30 | } else {
|
31 | this.headers[name] = value;
|
32 | }
|
33 | return this;
|
34 | }
|
35 |
|
36 | get length() {
|
37 | const length = this.getHeader('Content-Length');
|
38 | if (length) return length;
|
39 |
|
40 | if (typeof this.body === 'string') {
|
41 | return this.body.length;
|
42 | }
|
43 | return JSON.stringify(this.body).length;
|
44 | }
|
45 |
|
46 | toJSON() {
|
47 | return {
|
48 | body: this.body,
|
49 | elapsedTime: this.elapsedTime,
|
50 | url: this.url,
|
51 | headers: this.headers,
|
52 | statusCode: this.statusCode
|
53 | };
|
54 | }
|
55 |
|
56 | static create(opts) {
|
57 | const res = new Response();
|
58 | if (opts) {
|
59 | REQUIRED_PROPERTIES.forEach((property) => {
|
60 | res[property] = opts[property];
|
61 | });
|
62 | }
|
63 | return res;
|
64 | }
|
65 | }
|
66 |
|
67 | module.exports = Response;
|