/
request.ts
123 lines (106 loc) · 2.77 KB
/
request.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
import { HttpMethod } from "../interfaces";
export interface RequestOptions<TData> {
method?: HttpMethod | "*";
url?: string;
auth?: string;
params?: object | "*";
data?: TData | "*";
headers?: Headers;
}
export interface Headers {
[header: string]: string;
}
export default class Request<TData> {
method: HttpMethod | "*";
url: string;
auth: string;
params: object | "*";
data: TData | "*";
headers: Headers | "*";
constructor(opts?: RequestOptions<TData>) {
opts = opts || {};
this.method = opts.method || this.ANY;
this.url = opts.url || this.ANY;
this.auth = opts.auth || this.ANY;
this.params = opts.params || this.ANY;
this.data = opts.data || this.ANY;
this.headers = opts.headers || this.ANY;
}
get ANY(): "*" {
return "*";
}
attributeEqual(lhs: any, rhs: any): boolean {
if (lhs === this.ANY || rhs === this.ANY) {
return true;
}
lhs = lhs || undefined;
rhs = rhs || undefined;
if (typeof lhs !== typeof rhs) {
return false;
}
if (typeof lhs !== "object") {
return lhs === rhs;
}
return (
Object.entries(lhs)
.sort((a, b) => a[0].localeCompare(b[0]))
.toString() ===
Object.entries(rhs)
.sort((a, b) => a[0].localeCompare(b[0]))
.toString()
);
}
isEqual(other: Request<any>): boolean {
return (
this.attributeEqual(this.method, other.method) &&
this.attributeEqual(this.url, other.url) &&
this.attributeEqual(this.auth, other.auth) &&
this.attributeEqual(this.params, other.params) &&
this.attributeEqual(this.data, other.data) &&
this.attributeEqual(this.headers, other.headers)
);
}
toString(): string {
var auth = "";
if (this.auth && this.auth !== this.ANY) {
auth = this.auth + " ";
}
var params = "";
if (this.params && this.params !== this.ANY) {
params =
"?" +
Object.keys(this.params)
.map((key) =>
function (this: any) {
return key + "=" + this.params[key];
}.bind(this)()
)
.join("&");
}
var data = "";
if (this.data && this.data !== this.ANY) {
if (this.method === "get") {
data = "\n -G";
}
data =
data +
"\n" +
Object.entries(this.data)
.map((d) => {
return " -d " + d[0] + "=" + d[1];
})
.join("\n");
}
var headers = "";
if (this.headers && this.headers !== this.ANY) {
headers =
"\n" +
Object.entries(this.headers)
.map((header) => {
return " -H " + header[0] + "=" + header[1];
})
.join("\n");
}
return auth + this.method + " " + this.url + params + data + headers;
}
}