http-client.service.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { HttpService } from '@nestjs/axios'
  2. import { Injectable } from '@nestjs/common'
  3. import { lastValueFrom } from 'rxjs'
  4. import { ServiceResponse } from '@/response/response.interface'
  5. import { HttpStatusCode } from '@/response/status-code.enum'
  6. @Injectable()
  7. export class HttpClientService {
  8. constructor(private readonly httpService: HttpService) {}
  9. async get<T>(
  10. url: string,
  11. params?: Record<string, any>
  12. ): Promise<ServiceResponse<T>> {
  13. try {
  14. const responseObservable = await this.httpService.get<ServiceResponse<T>>(
  15. url,
  16. { params }
  17. )
  18. const { data } = await lastValueFrom(responseObservable)
  19. return data
  20. } catch (error) {
  21. return {
  22. code: HttpStatusCode.INTERNAL_SERVER_ERROR,
  23. msg: error.message,
  24. data: null as T
  25. }
  26. }
  27. }
  28. async post<T>(
  29. url: string,
  30. params?: Record<string, any>
  31. ): Promise<ServiceResponse<T>> {
  32. try {
  33. const responseObservable = await this.httpService.post<
  34. ServiceResponse<T>
  35. >(url, params, {
  36. headers: {
  37. 'Content-Type': 'application/json'
  38. }
  39. })
  40. const { data } = await lastValueFrom(responseObservable)
  41. return data
  42. } catch (error) {
  43. return {
  44. code: HttpStatusCode.INTERNAL_SERVER_ERROR,
  45. msg: error.message,
  46. data: null as T
  47. }
  48. }
  49. }
  50. }