apiRequestService.ts 2.4 KB

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