Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

69 lines
2.1KB

  1. import {useAuth} from "./authentication/use-auth";
  2. export default function useAuthorizedApi() {
  3. const {userData, signOut} = useAuth();
  4. return {
  5. get: request('GET'),
  6. post: request('POST'),
  7. put: request('PUT'),
  8. patch: request('PATCH'),
  9. doDelete: request('DELETE')
  10. };
  11. /**
  12. * @param {string} method
  13. * @return {function(*, *): Promise<*>}
  14. */
  15. function request(method) {
  16. /**
  17. * @param {string} url
  18. * @param {?any} [body]
  19. */
  20. return async (url, body) => {
  21. /** @type {RequestInit} **/
  22. const requestOptions = {
  23. method,
  24. headers: authHeader(url)
  25. };
  26. if (body) {
  27. if (body instanceof FormData) {
  28. requestOptions.body = body;
  29. } else {
  30. requestOptions.headers['Content-Type'] = 'application/json';
  31. requestOptions.body = JSON.stringify(body);
  32. }
  33. }
  34. return handleResponse(await fetch(url, requestOptions));
  35. }
  36. }
  37. function authHeader(url) {
  38. // return auth header with jwt if user is logged in and request is to the api url
  39. const token = userData?.access_token;
  40. const isLoggedIn = !!token;
  41. const isApiUrl = url.startsWith(window._env_.REACT_APP_API_URL);
  42. if (isLoggedIn && isApiUrl) {
  43. return {Authorization: `Bearer ${token}`};
  44. } else {
  45. return {};
  46. }
  47. }
  48. async function handleResponse(response) {
  49. const text = await response.text()
  50. const data = text && JSON.parse(text);
  51. if (!response.ok) {
  52. if ([401, 403].includes(response.status) && userData?.access_token) {
  53. // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
  54. localStorage.removeItem('user');
  55. await signOut();
  56. }
  57. const error = (data && data.message) || response.statusText;
  58. return Promise.reject(error);
  59. }
  60. return data;
  61. }
  62. }