Skip to content

Instantly share code, notes, and snippets.

@sagar290
Created August 20, 2022 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagar290/751b8242b9d4a73b5c46619679baa367 to your computer and use it in GitHub Desktop.
Save sagar290/751b8242b9d4a73b5c46619679baa367 to your computer and use it in GitHub Desktop.
import { HttpService } from '@nestjs/axios';
import { AxiosRequestHeaders } from 'axios';
import { Injectable } from '@nestjs/common';
import { firstValueFrom } from 'rxjs';
@Injectable()
export class BaseHttpService {
public baseUrl: string;
public secretKey: string;
private headers: AxiosRequestHeaders = {};
private response: any;
constructor(protected readonly httpService: HttpService) {}
setUrl(path: string) {
this.httpService.axiosRef.defaults.baseURL = this.baseUrl + path;
return this;
}
setHeaders(headers: object) {
// merge headers
this.headers = { ...this.headers, ...headers };
return this;
}
setBody(body: any) {
this.httpService.axiosRef.defaults.data = body;
return this;
}
async getUrl() {
return this.httpService.axiosRef.defaults.baseURL;
}
async getBody() {
return this.httpService.axiosRef.defaults.data;
}
async getHeaders(): Promise<AxiosRequestHeaders> {
return this.headers;
}
async post() {
return firstValueFrom(this.httpService.post(await this.getUrl(), await this.getBody(), await this.getHeaders()))
.then((res: any) => {
return this.interceptSuccessResponse(res).data;
})
.catch((err: any) => {
return this.interceptErrorRequest(err).data;
});
}
async get() {
return firstValueFrom(this.httpService.get(await this.getUrl(), await this.getHeaders()))
.then((res: any) => {
return this.interceptSuccessResponse(res).data;
})
.catch((err: any) => {
return this.interceptErrorRequest(err).data;
});
}
async put() {
return firstValueFrom(this.httpService.put(await this.getUrl(), await this.getBody(), await this.getHeaders()))
.then((res: any) => {
return this.interceptSuccessResponse(res).data;
})
.catch((err: any) => {
return this.interceptErrorRequest(err).data;
});
}
async patch() {
return firstValueFrom(this.httpService.patch(await this.getUrl(), await this.getBody(), await this.getHeaders()))
.then((res: any) => {
return this.interceptSuccessResponse(res).data;
})
.catch((err: any) => {
return this.interceptErrorRequest(err).data;
});
}
async delete() {
return firstValueFrom(this.httpService.delete(await this.getUrl(), await this.getHeaders()))
.then((res: any) => {
return this.interceptSuccessResponse(res).data;
})
.catch((err: any) => {
return this.interceptErrorRequest(err).data;
});
}
interceptErrorRequest(data: any): any {
return (this.response = data.response);
}
interceptSuccessResponse(data: any): any {
return (this.response = data);
}
getResponse(): any {
return this.response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment