index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. '/register/',
  46. userPayload
  47. )
  48. const avatar = `http://gravatar.com/avatar/${md5(autuUserData.email)}?d=identicon`
  49. const user = { email: autuUserData.email, avatar }
  50. await db
  51. .collection('users')
  52. .doc(userPayload.email)
  53. .set(user)
  54. commit('setUser', user)
  55. commit('setToken', autuUserData.idToken)
  56. commit('setLoading', false)
  57. } catch (error) {
  58. console.log(error)
  59. }
  60. }
  61. },
  62. getters: {
  63. headlines: state => state.headlines,
  64. loading: state => state.loading,
  65. category: state => state.category,
  66. country: state => state.country,
  67. isAuthenticated: state => !!state.token,
  68. user: state => state.user
  69. }
  70. })
  71. }
  72. export default createStore