index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { jwtDecode } from '../App'
  2. export function authReducer(state, { type, token }) {
  3. if (!state) {
  4. if (localStorage.authToken) {
  5. type = 'AUTH_LOGIN'
  6. token = localStorage.authToken
  7. } else {
  8. return {}
  9. }
  10. }
  11. if (type === 'AUTH_LOGIN') {
  12. let auth = jwtDecode(token)
  13. if (auth) {
  14. localStorage.authToken = token
  15. return { token, payload: auth }
  16. }
  17. }
  18. if (type === 'AUTH_LOGOUT') {
  19. localStorage.authToken = ''
  20. return {}
  21. }
  22. return state
  23. }
  24. export function promiseReducer(state = {}, { type, name, status, payload, error }) {
  25. if (type === 'PROMISE') {
  26. return {
  27. ...state,
  28. [name]: { status, payload: (state === 'PENDING' && state[name] && state[name].payload) || payload, error }
  29. }
  30. }
  31. return state
  32. }
  33. export function playerReducer(state, { type, track, playlist, duration, currentTime, volume, playlistIndex }) {
  34. if (!state || type === 'EJECT_TRACK') return {}
  35. if (type === 'PLAY_TRACK') return { ...state, 'isPlaying': true }
  36. if (type === 'PAUSE_TRACK') return { ...state, 'isPlaying': false }
  37. if (type === 'SET_CURRTIME') return { ...state, 'currentTime': currentTime }
  38. if (type === 'SET_DURATION') return { ...state, 'duration': duration }
  39. if (type === 'SET_VOLUME') return { ...state, 'volume': volume }
  40. if (type === 'SET_PLAYLIST') return { ...state, 'playlist': playlist}
  41. if (type === 'SET_INDEX') {
  42. console.log('SEt_INDEX', playlistIndex)
  43. return { ...state, 'playlistIndex': playlistIndex}
  44. }
  45. if (type === 'SET_TRACK') {
  46. return {
  47. isPlaying: false,
  48. track: track,
  49. playlist: playlist,
  50. duration: duration,
  51. currentTime: currentTime,
  52. volume: volume,
  53. playlistIndex:
  54. playlist.constructor.name === 'Array'? playlist.indexOf(track) : playlist.tracks.indexOf(track)
  55. }
  56. }
  57. return state
  58. }
  59. export const localStoreReducer = (reducer, localStorageName) => {
  60. return (
  61. (state, action) => {
  62. let newState
  63. if (!state && localStorage.getItem(localStorageName)) {
  64. newState = JSON.parse(localStorage.getItem(localStorageName))
  65. console.log(newState)
  66. } else {
  67. newState = reducer(state, action)
  68. localStorage.setItem(localStorageName, JSON.stringify(newState))
  69. }
  70. return newState
  71. }
  72. )
  73. }