apiRequestService.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * A basic api request service
  3. *
  4. * It will send basic http requests and returns raw results
  5. */
  6. import type { FetchOptions } from 'ofetch'
  7. import type { $Fetch } from 'nitropack'
  8. import type { AnyJson, AssociativeArray } from '~/types/data'
  9. import { HTTP_METHOD } from '~/types/enum/data'
  10. class ApiRequestService {
  11. private readonly fetch: $Fetch
  12. public constructor(fetch: $Fetch) {
  13. this.fetch = fetch
  14. }
  15. /**
  16. * Send a GET request
  17. *
  18. * @param url
  19. * @param query
  20. */
  21. public async get(
  22. url: string,
  23. query: AssociativeArray | string | null = null,
  24. ) {
  25. return await this.request(HTTP_METHOD.GET, url, null, query)
  26. }
  27. /**
  28. * Send a POST request
  29. *
  30. * @param url
  31. * @param body
  32. * @param query
  33. */
  34. public async post(
  35. url: string,
  36. body: string | AnyJson | null = null,
  37. query: AssociativeArray | string | null = null,
  38. ) {
  39. return await this.request(HTTP_METHOD.POST, url, body, query)
  40. }
  41. /**
  42. * Send a PUT request
  43. *
  44. * @param url
  45. * @param body
  46. * @param query
  47. */
  48. public async put(
  49. url: string,
  50. body: string | AnyJson | null = null,
  51. query: AssociativeArray | string | null = null,
  52. ) {
  53. return await this.request(HTTP_METHOD.PUT, url, body, query)
  54. }
  55. /**
  56. * Send a DELETE request
  57. *
  58. * @param url
  59. * @param query
  60. */
  61. public async delete(
  62. url: string,
  63. query: AssociativeArray | string | null = null,
  64. ) {
  65. return await this.request(HTTP_METHOD.DELETE, url, null, query)
  66. }
  67. /**
  68. * Send an http request
  69. *
  70. * @param method
  71. * @param url
  72. * @param body
  73. * @param query
  74. * @protected
  75. */
  76. protected async request(
  77. method: HTTP_METHOD,
  78. url: string,
  79. body: string | AnyJson | null = null,
  80. query: AssociativeArray | string | null = null,
  81. ): Promise<Response> {
  82. const config: FetchOptions = { method }
  83. if (query && typeof query !== 'string') {
  84. config.query = query
  85. }
  86. if (method === HTTP_METHOD.POST || method === HTTP_METHOD.PUT) {
  87. config.body = body
  88. }
  89. // @ts-expect-error TODO: solve the type mismatch
  90. return await this.fetch(url, config)
  91. }
  92. }
  93. export default ApiRequestService