wallet-core/src/http.ts

95 lines
2.4 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;
responseText: string;
}
2017-05-24 16:14:23 +02:00
/**
* The request library is bundled into an interface to make mocking easy.
*/
export interface HttpRequestLibrary {
get(url: string): Promise<HttpResponse>;
postJson(url: string, body: any): Promise<HttpResponse>;
postForm(url: string, form: any): 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 {
2017-05-24 16:14:23 +02:00
private req(method: string,
2017-05-28 01:10:54 +02:00
url: string,
options?: any): Promise<HttpResponse> {
return new Promise<HttpResponse>((resolve, reject) => {
2017-05-28 01:10:54 +02:00
const myRequest = new XMLHttpRequest();
myRequest.open(method, url);
if (options && options.req) {
myRequest.send(options.req);
} else {
myRequest.send();
2016-01-05 01:13:48 +01:00
}
myRequest.addEventListener("readystatechange", (e) => {
2017-05-28 01:10:54 +02:00
if (myRequest.readyState === XMLHttpRequest.DONE) {
const resp = {
responseText: myRequest.responseText,
status: myRequest.status,
};
resolve(resp);
}
});
2016-01-05 01:13:48 +01:00
});
}
2016-01-05 01:13:48 +01:00
get(url: string) {
return this.req("get", url);
}
2016-01-05 01:13:48 +01:00
postJson(url: string, body: any) {
return this.req("post", url, {req: JSON.stringify(body)});
}
2016-01-05 14:20:13 +01:00
postForm(url: string, form: any) {
return this.req("post", url, {req: form});
}
2016-01-05 01:13:48 +01:00
}
2017-05-24 16:14:23 +02:00
/**
* Exception thrown on request errors.
*/
export class RequestException {
2017-05-24 16:14:23 +02:00
constructor(public detail: any) {
2016-01-05 01:13:48 +01:00
}
2016-03-01 19:46:20 +01:00
}