1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import Vuex from 'vuex'
- import md5 from 'md5'
- import db from '~/plugins/firestore'
- import { saveUserData, clearUserData } from '~/utils'
- const createStore = () => {
- return new Vuex.Store({
- state: {
- headlines: [],
- loading: false,
- category: '',
- token: null,
- country: 'us',
- user: null
- },
- mutations: {
- setHeadLines (state, headlines) {
- state.headlines = headlines
- },
- setLoading (state, loading) {
- state.loading = loading
- },
- setCategory (state, category) {
- state.category = category
- },
- setCountry (state, country) {
- state.country = country
- },
- setToken (state, token) {
- state.token = token
- },
- setUser (state, user) {
- state.user = user
- },
- clearToken: state => (state.token = null),
- clearUser: state => (state.user = null)
- },
- actions: {
- async loadHeadLines ({ commit }, apiUrl) {
- commit('setLoading', true)
- const { articles } = await this.$axios.$get(apiUrl)
- commit('setLoading', false)
- commit('setHeadLines', articles)
- },
- async authenticateUser ({ commit }, userPayload) {
- try {
- commit('setLoading', true)
- const autuUserData = await this.$axios.$post(
- `/${userPayload.action}/`,
- {
- email: userPayload.email,
- password: userPayload.password,
- resturnSecureToken: userPayload.resturnSecureToken
- }
- )
- let user
- if (userPayload.action === 'register') {
- const avatar = `http://gravatar.com/avatar/${md5(autuUserData.email)}?d=identicon`
- user = { email: autuUserData.email, avatar }
- await db
- .collection('users')
- .doc(userPayload.email)
- .set(user)
- } else {
- const loginRef = db.collection('users').doc(userPayload.email)
- const loggedInUser = await loginRef.get()
- user = loggedInUser.data()
- }
- console.log(autuUserData)
- commit('setUser', user)
- commit('setToken', autuUserData.idToken)
- commit('setLoading', false)
- saveUserData(autuUserData, user)
- } catch (error) {
- console.log(error)
- }
- },
- setLogoutTimer ({ dispatch }, interval) {
- setTimeout(() => dispatch('logoutUser'), interval)
- },
- logoutUser ({ commit }) {
- commit('clearToken')
- commit('clearUser')
- clearUserData()
- }
- },
- getters: {
- headlines: state => state.headlines,
- loading: state => state.loading,
- category: state => state.category,
- country: state => state.country,
- isAuthenticated: state => !!state.token,
- user: state => state.user
- }
- })
- }
- export default createStore
|