index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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') return { ...state, 'playlistIndex': playlistIndex}
  42. if (type === 'SET_TRACK') {
  43. return {
  44. isPlaying: false,
  45. track: track,
  46. playlist: playlist,
  47. duration: duration,
  48. currentTime: currentTime,
  49. volume: volume,
  50. playlistIndex:
  51. playlist.constructor.name === 'Array'? playlist.indexOf(track) : playlist.tracks.indexOf(track)
  52. }
  53. }
  54. return state
  55. }
  56. export const localStoreReducer = (reducer, localStorageName) => {
  57. return (
  58. (state, action) => {
  59. let newState
  60. if (!state && localStorage.getItem(localStorageName)) {
  61. newState = JSON.parse(localStorage.getItem(localStorageName))
  62. console.log(newState)
  63. } else {
  64. newState = reducer(state, action)
  65. localStorage.setItem(localStorageName, JSON.stringify(newState))
  66. }
  67. return newState
  68. }
  69. )
  70. }