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> = {};
|
2020-09-07 22:45:52 +02:00
|
|
|
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) {
|
2020-09-07 22:45:52 +02:00
|
|
|
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));
|
|
|
|
}
|
|
|
|
|
2020-09-07 22:45:52 +02:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|