55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
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, status: number) => void;
|
|
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, this.request.status);
|
|
} 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, status: number) => void): void
|
|
{
|
|
this.onSuccess = callback;
|
|
}
|
|
|
|
public setOnError(callback: (responseText: string, status: number) => void): void
|
|
{
|
|
this.onError = callback;
|
|
}
|
|
}
|