apiRequestService.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /**
  2. * A basic api request service
  3. *
  4. * It will send basic http requests and returns raw results
  5. */
  6. import {AssociativeArray} from "~/types/data";
  7. import {$Fetch} from "nitropack";
  8. import {FetchOptions} from "ohmyfetch";
  9. import {HTTP_METHOD} from "~/types/enum/data";
  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, null, query)
  28. }
  29. /**
  30. * Send a POST request
  31. *
  32. * @param url
  33. * @param body
  34. * @param params
  35. * @param query
  36. */
  37. public async post(
  38. url: string,
  39. body: string | null = null,
  40. params: AssociativeArray | null = null,
  41. query: AssociativeArray | null = null
  42. ) {
  43. return await this.request(HTTP_METHOD.POST, url, body, params, query)
  44. }
  45. /**
  46. * Send a PUT request
  47. *
  48. * @param url
  49. * @param body
  50. * @param params
  51. * @param query
  52. */
  53. public async put(
  54. url: string,
  55. body: string | null = null,
  56. params: AssociativeArray | null = null,
  57. query: AssociativeArray | null = null
  58. ) {
  59. return await this.request(HTTP_METHOD.PUT, url, body, params, query)
  60. }
  61. /**
  62. * Send a DELETE request
  63. *
  64. * @param url
  65. * @param query
  66. */
  67. public async delete(
  68. url: string,
  69. query: AssociativeArray | null = null
  70. ) {
  71. return await this.request(HTTP_METHOD.DELETE, url, null, null, query)
  72. }
  73. /**
  74. * Send an http request
  75. *
  76. * @param method
  77. * @param url
  78. * @param body
  79. * @param params
  80. * @param query
  81. * @private
  82. */
  83. private async request(
  84. method: HTTP_METHOD,
  85. url: string,
  86. body: string | null = null,
  87. params: AssociativeArray | null = null,
  88. query: AssociativeArray | null = null
  89. ): Promise<Response> {
  90. const config: FetchOptions = { method }
  91. if (params) {
  92. config.params = params
  93. }
  94. if (query) {
  95. config.query = query
  96. }
  97. if (method === HTTP_METHOD.POST || method === HTTP_METHOD.PUT) {
  98. config.body = body
  99. }
  100. return this.fetch(url, config)
  101. }
  102. }
  103. export default ApiRequestService