-
Notifications
You must be signed in to change notification settings - Fork 0
/
requester.ts
189 lines (171 loc) · 4.61 KB
/
requester.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
import http from "http";
import https from "https";
// https://stackoverflow.com/questions/71294230/how-can-i-use-native-fetch-with-node-in-typescript-node-v17-6
import type { HeadersInit } from "undici";
/**
* Requesters return this.
*/
export interface Response {
/**
* The text response. `null` in case of a request error.
*/
text: string | null;
/**
* `JSON.parses` the results. `null` in cases of request or parsing errors.
*/
json: any | null /* eslint-disable-line @typescript-eslint/no-explicit-any */;
/**
* Error if the request failed or `null` if it succeeded.
*/
error: string | null;
}
/**
* Requesters make the requests and return a responses.
*/
export interface Requester {
/**
* Set the request headers
* @param headers request headers
*/
addHeaders(headers: http.OutgoingHttpHeaders | HeadersInit): void;
/**
* GET the Parameter or Secret
* @param url the localhost url endpoint for the Parameter or Secret
*/
get(url: string): Promise<Response>;
}
/**
* A Response implementor
*/
export class HttpResponse implements Response {
/**
* Construct a Response for a successful request
* @param data the response
* @returns a success response where `error: null`
*/
static successResponse(data: string): Response {
return new HttpResponse(data);
}
/**
* Construct a Response for a failed request
* @param data the response
* @param statusCode the HTTP status code
* @param statusMessage the HTTP status message
* @returns a failed response where `text: null` and `json: null`
*/
static failureResponse(
data: string,
statusCode: number | string,
statusMessage: string,
): Response {
return new HttpResponse(`${statusCode} ${statusMessage} - ${data}`, true);
}
private constructor(
private data: string,
public isError: boolean = false,
) {}
get text(): string | null {
return this.isError ? null : this.data;
}
get json() {
try {
if (this.isError) return null;
return JSON.parse(this.data);
} catch {
return null;
}
}
get error(): string | null {
return this.isError ? this.data : null;
}
}
/**
* A bare-bones HTTP GET client.
*
* Implementation: NodeJS core `http` library.
*/
export class HttpRequester implements Requester {
public headers: http.OutgoingHttpHeaders;
constructor(headers?: http.OutgoingHttpHeaders) {
this.headers = {
"User-Agent": "Other",
...headers,
};
}
addHeaders(headers: http.OutgoingHttpHeaders): void {
this.headers = headers;
}
async get(url: string): Promise<Response> {
// https://developer.mozilla.org/en-US/docs/Web/API/fetch
const res = await new Promise<http.IncomingMessage>((resolve) => {
const components = new URL(url);
const getter = components.protocol.startsWith("https") ? https : http;
getter.get(url, { headers: this.headers }, resolve);
});
return new Promise<string>((resolve, reject) => {
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("error", (err) => reject(err));
res.on("end", () => resolve(data));
})
.then((data) => {
return res.statusCode === 200
? HttpResponse.successResponse(data)
: HttpResponse.failureResponse(
data,
res.statusCode ?? "<?>",
res.statusMessage ?? "<Unknown Status>",
);
})
.catch((err) =>
HttpResponse.failureResponse(
err,
res.statusCode ?? "<?>",
"<Rejection>",
),
);
}
}
/**
* A Native Fetch GET client.
*
* Implementation: NodeJS `fetch` library.
* Requires NoeJS 18 or higher.
*/
export class FetchRequester implements Requester {
public headers: HeadersInit;
constructor(headers?: HeadersInit) {
this.headers = {
"User-Agent": "Other",
...headers,
};
}
addHeaders(headers: HeadersInit): void {
this.headers = headers;
}
/*global fetch*/
async get(url: string): Promise<Response> {
try {
const res = await fetch(url, { headers: this.headers });
if (res.ok) {
const text = await res.text();
const json = JSON.parse(text);
return {
text,
json,
error: null,
};
} else {
return HttpResponse.failureResponse(
"Response is not OK",
res.status,
res.statusText,
);
}
} catch (err: unknown) {
const message =
err instanceof Error ? err.message : "Unknown Server Error";
return HttpResponse.failureResponse(message, "503", "Server Error");
}
}
}