MireaFrontend/src/api/RequestBuilder.ts

103 lines
2.4 KiB
TypeScript

import {HttpHeaders} from "@angular/common/http";
export interface SetRequestBuilderAfterBuild {
setRequestBuilder(request: RequestData): void;
}
export interface RequestData {
endpoint: string;
queryParams: Record<string, string | number | boolean | Array<any> | null> | null;
httpHeaders: HttpHeaders;
data: any;
silenceMode: boolean;
}
export class RequestBuilder {
private endpoint: string = '';
private queryParams: Record<string, string | number | boolean | Array<any> | null> | null = null;
private httpHeaders: HttpHeaders = new HttpHeaders();
private data: any = null;
private silenceMode: boolean = false;
private readonly object: any;
constructor(obj: any) {
this.object = obj;
}
public setEndpoint(endpoint: string): this {
this.endpoint = endpoint;
return this;
}
public setQueryParams(queryParams: Record<string, string | number | boolean | Array<any> | null>): RequestBuilder {
this.queryParams = queryParams;
return this;
}
public addHeaders(headers: Record<string, string>): RequestBuilder {
Object.keys(headers).forEach(key => {
this.httpHeaders = this.httpHeaders.set(key, headers[key]);
});
return this;
}
public setData(data: any): RequestBuilder {
this.data = data;
return this;
}
public setSilenceMode(silence: boolean): RequestBuilder {
this.silenceMode = silence;
return this;
}
public build<Type>(): Type {
(this.object as SetRequestBuilderAfterBuild).setRequestBuilder({
endpoint: this.endpoint,
queryParams: this.queryParams,
httpHeaders: this.httpHeaders,
data: this.data,
silenceMode: this.silenceMode
});
return this.object as Type;
}
public getEndpoint(): string {
return this.endpoint;
}
public getQueryParams(): Record<string, string | number | boolean | Array<any> | null> | null {
return this.queryParams;
}
public getHttpHeaders(): HttpHeaders {
return this.httpHeaders;
}
public getData(): any {
return this.data;
}
public getSilenceMode(): boolean {
return this.silenceMode;
}
public static getStandardRequestData(): RequestData {
return {
endpoint: '',
queryParams: null,
httpHeaders: new HttpHeaders(),
data: null,
silenceMode: false
}
}
public reset(): void {
this.endpoint = '';
this.queryParams = null;
this.httpHeaders = new HttpHeaders();
this.data = null;
this.silenceMode = false;
}
}