useApi.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { useUser } from "~/store/useUser"
  2. import { $fetch } from 'ofetch'
  3. import { useLogger } from "./useLogger"
  4. interface TException {
  5. error: string;
  6. code: number;
  7. }
  8. export function useApi() {
  9. const { public: { API_URL } } = useRuntimeConfig()
  10. const user = useUser()
  11. const log = useLogger('useApi')
  12. function showError(data: TException) {
  13. if (data.hasOwnProperty('code') && data.hasOwnProperty('error')) {
  14. alert(data.error)
  15. log.error(JSON.stringify(data))
  16. }
  17. return data;
  18. }
  19. const instance = $fetch.create({
  20. baseURL: API_URL,
  21. onRequest(ctx) {
  22. if (!user.data.token && ctx.request !== '/login')
  23. navigateTo('/auth')
  24. },
  25. onResponse(ctx) {
  26. const statusCode = ctx.response.status;
  27. if (statusCode > 300)
  28. showError(ctx.response._data)
  29. // TODO: add refreshing token
  30. },
  31. })
  32. const api = {
  33. get: (url: string, params?: object) => {
  34. return instance(url, {
  35. method: "GET",
  36. params,
  37. })
  38. },
  39. post: (url: string, body?: object) => {
  40. return instance(url, {
  41. method: "POST",
  42. body,
  43. })
  44. },
  45. put: (url: string, body?: object) => {
  46. return instance(url, {
  47. method: "PUT",
  48. body,
  49. })
  50. },
  51. DELETE: (url: string, body?: object) => {
  52. return instance(url, {
  53. method: "DELETE",
  54. body,
  55. })
  56. }
  57. }
  58. return api;
  59. }