ringfinger/js/api/ApiRequest.ts

55 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

2020-09-06 12:07:26 +02:00
import RequestMethod from "./RequestMethod.js";
export default class ApiRequest
{
protected static BASE_URL: string = 'api/v1/';
protected request: XMLHttpRequest;
protected method: RequestMethod;
protected url: string;
protected parameters: Record<string, any> = {};
protected onSuccess: (responseText: string) => void;
2020-09-06 12:07:26 +02:00
protected onError: (responseText: string, status: number) => void;
public constructor(url: string, method: RequestMethod)
{
this.url = ApiRequest.BASE_URL + url;
this.method = method;
this.request = new XMLHttpRequest();
this.request.open(this.method, this.url);
this.onSuccess = () => {};
this.onError = () => {};
}
public addParameter(name: string, value: any): void
{
this.parameters[name] = value;
}
public submit(): void
{
this.request.onreadystatechange = () => {
if (this.request.readyState === 4) {
if (this.request.status === 200) {
this.onSuccess(this.request.responseText);
2020-09-06 12:07:26 +02:00
} else {
this.onError(this.request.responseText, this.request.status);
}
}
}
this.request.setRequestHeader('Content-Type', 'application/json');
this.request.send(JSON.stringify(this.parameters));
}
public setOnSuccess(callback: (responseText: string) => void): void
2020-09-06 12:07:26 +02:00
{
this.onSuccess = callback;
}
public setOnError(callback: (responseText: string, status: number) => void): void
{
this.onError = callback;
}
}