From aa2eab9a4cf9addcf2ca59407429eab0d9d2cb6a Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Thu, 27 Jun 2024 01:46:32 +0300 Subject: [PATCH] feat: add request builder --- src/api/RequestBuilder.ts | 102 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 src/api/RequestBuilder.ts diff --git a/src/api/RequestBuilder.ts b/src/api/RequestBuilder.ts new file mode 100644 index 0000000..a279bf2 --- /dev/null +++ b/src/api/RequestBuilder.ts @@ -0,0 +1,102 @@ +import {HttpHeaders} from "@angular/common/http"; + +export interface SetRequestBuilderAfterBuild { + setRequestBuilder(request: RequestData): void; +} + +export interface RequestData { + endpoint: string; + queryParams: Record | null> | null; + httpHeaders: HttpHeaders; + data: any; + silenceMode: boolean; +} + +export class RequestBuilder { + private endpoint: string = ''; + private queryParams: Record | 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 | null>): RequestBuilder { + this.queryParams = queryParams; + return this; + } + + public addHeaders(headers: Record): 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 { + (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 | 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; + } +}