123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- import { HttpService } from '@nestjs/axios'
- import { Injectable } from '@nestjs/common'
- import { lastValueFrom } from 'rxjs'
- import { ServiceResponse } from '@/response/response.interface'
- import { HttpStatusCode } from '@/response/status-code.enum'
- @Injectable()
- export class HttpClientService {
- constructor(private readonly httpService: HttpService) {}
- async get<T>(
- url: string,
- params?: Record<string, any>
- ): Promise<ServiceResponse<T>> {
- try {
- const responseObservable = await this.httpService.get<ServiceResponse<T>>(
- url,
- { params }
- )
- const { data } = await lastValueFrom(responseObservable)
- return data
- } catch (error) {
- return {
- code: HttpStatusCode.INTERNAL_SERVER_ERROR,
- msg: error.message,
- data: null as T
- }
- }
- }
- async post<T>(
- url: string,
- params?: Record<string, any>
- ): Promise<ServiceResponse<T>> {
- try {
- const responseObservable = await this.httpService.post<
- ServiceResponse<T>
- >(url, params, {
- headers: {
- 'Content-Type': 'application/json'
- }
- })
- const { data } = await lastValueFrom(responseObservable)
- return data
- } catch (error) {
- return {
- code: HttpStatusCode.INTERNAL_SERVER_ERROR,
- msg: error.message,
- data: null as T
- }
- }
- }
- }
|