index.js 2.4 KB

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