wallet-core/src/util/http.ts

167 lines
4.7 KiB
TypeScript
Raw Normal View History

2016-01-05 01:13:48 +01:00
/*
This file is part of TALER
(C) 2016 GNUnet e.V.
TALER is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
TALER is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
2016-07-07 17:59:29 +02:00
TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
2016-01-05 01:13:48 +01:00
*/
2016-01-05 15:42:46 +01:00
/**
* Helpers for doing XMLHttpRequest-s that are based on ES6 promises.
2017-05-24 16:14:23 +02:00
* Allows for easy mocking for test cases.
2016-01-05 15:42:46 +01:00
*/
2017-05-24 16:14:23 +02:00
/**
* An HTTP response that is returned by all request methods of this library.
*/
export interface HttpResponse {
2016-01-05 01:13:48 +01:00
status: number;
2019-12-09 19:59:08 +01:00
headers: Headers;
2019-12-09 13:29:11 +01:00
json(): Promise<any>;
text(): Promise<string>;
}
export interface HttpRequestOptions {
headers?: { [name: string]: string };
2016-01-05 01:13:48 +01:00
}
export enum HttpResponseStatus {
Ok = 200,
Gone = 210,
}
2019-12-09 19:59:08 +01:00
/**
* Headers, roughly modeled after the fetch API's headers object.
*/
export class Headers {
private headerMap = new Map<string, string>();
get(name: string): string | null {
const r = this.headerMap.get(name.toLowerCase());
if (r) {
return r;
}
return null;
}
set(name: string, value: string): void {
const normalizedName = name.toLowerCase();
const existing = this.headerMap.get(normalizedName);
if (existing !== undefined) {
this.headerMap.set(normalizedName, existing + "," + value);
} else {
this.headerMap.set(normalizedName, value);
}
}
}
2017-05-24 16:14:23 +02:00
/**
2019-12-09 13:29:11 +01:00
* The request library is bundled into an interface to m responseJson: object & any;ake mocking easy.
2017-05-24 16:14:23 +02:00
*/
export interface HttpRequestLibrary {
2019-12-09 13:29:11 +01:00
get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse>;
postJson(
url: string,
body: any,
opt?: HttpRequestOptions,
): Promise<HttpResponse>;
}
2017-05-24 16:14:23 +02:00
/**
* An implementation of the [[HttpRequestLibrary]] using the
* browser's XMLHttpRequest.
*/
2019-07-21 23:50:10 +02:00
export class BrowserHttpLib implements HttpRequestLibrary {
private req(
method: string,
url: string,
2019-12-09 13:29:11 +01:00
requestBody?: any,
options?: HttpRequestOptions,
): Promise<HttpResponse> {
return new Promise<HttpResponse>((resolve, reject) => {
2017-05-28 01:10:54 +02:00
const myRequest = new XMLHttpRequest();
myRequest.open(method, url);
2019-12-09 13:29:11 +01:00
if (options?.headers) {
for (const headerName in options.headers) {
myRequest.setRequestHeader(headerName, options.headers[headerName]);
}
}
myRequest.setRequestHeader;
if (requestBody) {
myRequest.send(requestBody);
} else {
myRequest.send();
2016-01-05 01:13:48 +01:00
}
2020-03-30 12:39:32 +02:00
myRequest.onerror = (e) => {
console.error("http request error");
reject(Error("could not make XMLHttpRequest"));
};
2020-03-30 12:39:32 +02:00
myRequest.addEventListener("readystatechange", (e) => {
2017-05-28 01:10:54 +02:00
if (myRequest.readyState === XMLHttpRequest.DONE) {
if (myRequest.status === 0) {
reject(
Error(
2019-12-09 13:29:11 +01:00
"HTTP Request failed (status code 0, maybe URI scheme is wrong?)",
),
);
return;
}
2020-04-06 20:02:01 +02:00
const makeJson = async (): Promise<any> => {
2019-12-09 13:29:11 +01:00
let responseJson;
try {
responseJson = JSON.parse(myRequest.responseText);
} catch (e) {
throw Error("Invalid JSON from HTTP response");
}
if (responseJson === null || typeof responseJson !== "object") {
throw Error("Invalid JSON from HTTP response");
}
return responseJson;
};
const headers = myRequest.getAllResponseHeaders();
const arr = headers.trim().split(/[\r\n]+/);
// Create a map of header names to values
2019-12-09 19:59:08 +01:00
const headerMap = new Headers();
2020-03-30 12:39:32 +02:00
arr.forEach(function (line) {
2019-12-09 13:29:11 +01:00
const parts = line.split(": ");
const header = parts.shift();
const value = parts.join(": ");
2019-12-09 19:59:08 +01:00
headerMap.set(header!, value);
2019-12-09 13:29:11 +01:00
});
const resp: HttpResponse = {
status: myRequest.status,
2019-12-09 13:29:11 +01:00
headers: headerMap,
json: makeJson,
text: async () => myRequest.responseText,
};
resolve(resp);
}
});
2016-01-05 01:13:48 +01:00
});
}
2016-01-05 01:13:48 +01:00
2020-04-06 20:02:01 +02:00
get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> {
2019-12-09 13:29:11 +01:00
return this.req("get", url, undefined, opt);
}
2016-01-05 01:13:48 +01:00
2020-04-06 20:02:01 +02:00
postJson(url: string, body: any, opt?: HttpRequestOptions): Promise<HttpResponse> {
2019-12-09 13:29:11 +01:00
return this.req("post", url, JSON.stringify(body), opt);
}
2016-01-05 14:20:13 +01:00
2020-04-06 20:02:01 +02:00
stop(): void {
2019-12-09 13:29:11 +01:00
// Nothing to do
}
2016-01-05 01:13:48 +01:00
}