UNPKG

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