index.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import Vuex from 'vuex'
  2. import md5 from 'md5'
  3. import db from '~/plugins/firestore'
  4. import { saveUserData, clearUserData } from '~/utils'
  5. const createStore = () => {
  6. return new Vuex.Store({
  7. state: {
  8. headlines: [],
  9. loading: false,
  10. category: '',
  11. token: null,
  12. country: 'us',
  13. user: null
  14. },
  15. mutations: {
  16. setHeadLines (state, headlines) {
  17. state.headlines = headlines
  18. },
  19. setLoading (state, loading) {
  20. state.loading = loading
  21. },
  22. setCategory (state, category) {
  23. state.category = category
  24. },
  25. setCountry (state, country) {
  26. state.country = country
  27. },
  28. setToken (state, token) {
  29. state.token = token
  30. },
  31. setUser (state, user) {
  32. state.user = user
  33. },
  34. clearToken: state => (state.token = null),
  35. clearUser: state => (state.user = null)
  36. },
  37. actions: {
  38. async loadHeadLines ({ commit }, apiUrl) {
  39. commit('setLoading', true)
  40. const { articles } = await this.$axios.$get(apiUrl)
  41. commit('setLoading', false)
  42. commit('setHeadLines', articles)
  43. },
  44. async authenticateUser ({ commit }, userPayload) {
  45. try {
  46. commit('setLoading', true)
  47. const autuUserData = await this.$axios.$post(
  48. `/${userPayload.action}/`,
  49. {
  50. email: userPayload.email,
  51. password: userPayload.password,
  52. resturnSecureToken: userPayload.resturnSecureToken
  53. }
  54. )
  55. let user
  56. if (userPayload.action === 'register') {
  57. const avatar = `http://gravatar.com/avatar/${md5(autuUserData.email)}?d=identicon`
  58. user = { email: autuUserData.email, avatar }
  59. await db
  60. .collection('users')
  61. .doc(userPayload.email)
  62. .set(user)
  63. } else {
  64. const loginRef = db.collection('users').doc(userPayload.email)
  65. const loggedInUser = await loginRef.get()
  66. user = loggedInUser.data()
  67. }
  68. // console.log(autuUserData)
  69. commit('setUser', user)
  70. commit('setToken', autuUserData.idToken)
  71. commit('setLoading', false)
  72. saveUserData(autuUserData, user)
  73. } catch (error) {
  74. // console.log(error)
  75. }
  76. },
  77. setLogoutTimer ({ dispatch }, interval) {
  78. setTimeout(() => dispatch('logoutUser'), interval)
  79. },
  80. logoutUser ({ commit }) {
  81. commit('clearToken')
  82. commit('clearUser')
  83. clearUserData()
  84. }
  85. },
  86. getters: {
  87. headlines: state => state.headlines,
  88. loading: state => state.loading,
  89. category: state => state.category,
  90. country: state => state.country,
  91. isAuthenticated: state => !!state.token,
  92. user: state => state.user
  93. }
  94. })
  95. }
  96. export default createStore