apiRequestService.ts 2.2 KB

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