promiseReducer.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { actionAuthLogin } from "./authReducer";
  2. import { store } from "./store";
  3. export function promiseReducer(state={}, {type, name, status, payload, error}) {
  4. if (type === 'PROMISE'){
  5. return {
  6. ...state,
  7. [name]:{status, payload, error}
  8. }
  9. }
  10. return state
  11. }
  12. const actionPending = name => ({type:'PROMISE',name, status: 'PENDING'})
  13. const actionFulfilled = (name,payload) => ({type:'PROMISE',name, status: 'FULFILLED', payload})
  14. const actionRejected = (name,error) => ({type:'PROMISE',name, status: 'REJECTED', error})
  15. export const actionPromise = (name, promise) =>
  16. async dispatch => {
  17. dispatch(actionPending(name))
  18. try {
  19. let payload = await promise
  20. dispatch(actionFulfilled(name, payload))
  21. return payload
  22. }
  23. catch(error){
  24. dispatch(actionRejected(name, error))
  25. }
  26. }
  27. export const backendURL = 'http://player-api/api';
  28. const getGQL = (backendURL) =>
  29. (plusurl) => fetch(backendURL+plusurl, {
  30. method: 'GET',
  31. headers: {
  32. "Content-Type": "application/json",
  33. ...(localStorage.authToken ? {"Authorization": "Bearer " + localStorage.authToken} : {})
  34. }
  35. }).then(res => res.json())
  36. .then(data => {
  37. return data;
  38. // if (data.data){
  39. // return Object.values(data.data)[0]
  40. // }
  41. // else {throw new Error(JSON.stringify(data.errors))}
  42. })
  43. export const gql = getGQL(backendURL);
  44. export const actionAllPlaylists = () =>
  45. actionPromise('allPlaylists', gql('/playlists'))
  46. export const actionUsersPlaylists = (id) =>
  47. actionPromise('usersPlaylists', gql('/profile/' + id + '/playlists'))
  48. export const actionPlaylistById = (_id) => {
  49. let link = (((window.location.href.split('/')[3] === 'artists' || window.location.href.split('/')[3]) === 'albums') ? 'albums' : 'playlists');
  50. return (actionPromise('plstById', gql('/'+link+'/'+_id)))
  51. }
  52. export const actionNowPlaylist = (_id) =>
  53. actionPromise('plstnow', gql('/playlists/'+_id))
  54. export const actionFullLogin = async function(login, password) {
  55. let token = await gql("query userLogin($login: String, $password: String) {login(login: $login, password: $password)}",
  56. {"login": login, "password": password});
  57. store.dispatch(actionAuthLogin(token));
  58. };
  59. export const actionArtistById = (_id) =>
  60. actionPromise('artistById', gql('/artists/'+_id))
  61. export const actionSearch = (search) =>
  62. actionPromise('searchResult', gql('/search?search='+search))