Api.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import {useEffect, useState} from 'react';
  2. import {getQueryString} from './utils';
  3. const domain = '';
  4. export function storeToken(token) {
  5. localStorage.setItem('token', token);
  6. }
  7. export function loadToken() {
  8. return localStorage.getItem('token');
  9. }
  10. export function login(info) {
  11. if (!info) return null;
  12. return {url: '/api/login',
  13. options: {
  14. method: 'POST',
  15. body: JSON.stringify(info),
  16. }};
  17. }
  18. export function logout() {
  19. localStorage.removeItem('token');
  20. }
  21. export function getUser() { return {url: '/api/user'} };
  22. export function getCategories() { return {url: '/api/cat'} };
  23. export function getCategory(cat, params) {
  24. return {url: `/api/cat/${cat}?${getQueryString(params)}`};
  25. }
  26. export function getAlbums(params) {
  27. return {url: `/api/cat/album?${getQueryString(params)}`};
  28. }
  29. export function getTracks(album_id) {
  30. return {url: `/api/album/${album_id}/tracks`};
  31. }
  32. export const initialState = (initialData) => {return {loading: false, error: null, data: initialData}}
  33. export function fetchReducer(s, a) {
  34. switch (a.type) {
  35. case 'FETCH_INIT': return {...s, loading: true, error: null};
  36. case 'FETCH_SUCCESS': return {...s, loading: false, error: null, data: a.payload};
  37. case 'FETCH_FAIL': return {...s, loading: false, error: a.payload};
  38. default: throw new Error();
  39. }
  40. }
  41. export const useFetch = (initialUrl, dispatch, typePrefix) => {
  42. const [url, setUrl] = useState(initialUrl);
  43. const prefix = typePrefix || 'FETCH';
  44. useEffect(() => {
  45. if (!url) return;
  46. let mounted = true;
  47. const fetchData = async () => {
  48. dispatch({type:`${prefix}_INIT`});
  49. try {
  50. const data = await request(url.url, url.options);
  51. mounted && dispatch({type:`${prefix}_SUCCESS`, payload: data});
  52. } catch (err) {
  53. mounted && dispatch({type:`${prefix}_FAIL`, payload: err});
  54. }
  55. };
  56. fetchData();
  57. return () => { mounted = false; };
  58. }, [url,prefix,dispatch]);
  59. return setUrl;
  60. };
  61. export function request(url, options) {
  62. // performs api calls sending the required authentication headers
  63. const headers = {
  64. Accept: 'application/json',
  65. 'Content-Type': 'application/json',
  66. };
  67. // Setting Authorization header
  68. // Authorization: Bearer xxxxxxx.xxxxxxxx.xxxxxx
  69. if (loadToken()) {
  70. headers['Authorization'] = 'Bearer ' + loadToken();
  71. }
  72. return fetch(`${domain}${url}`, {
  73. headers,
  74. ...options,
  75. })
  76. .then(_checkStatus)
  77. .then(response => response.json());
  78. }
  79. function _checkStatus(response) {
  80. // raises an error in case response status is not a success
  81. if (response.status >= 200 && response.status < 300) {
  82. // Success status lies between 200 to 300
  83. return response;
  84. } else {
  85. var error = new Error(response.statusText);
  86. error.response = response;
  87. throw error;
  88. }
  89. }