added new login code and testing components

This commit is contained in:
2019-03-21 16:13:57 +01:00
parent 18f22fdffa
commit e04da5b273
11 changed files with 587 additions and 9 deletions

View File

@@ -1,16 +1,110 @@
import Vue from 'vue';
import Vuex from 'vuex';
// imports of AJAX functions will go here
import { fetchSurveys, fetchSurvey, saveSurveyResponse, postNewSurvey, authenticate, register } from '@/api'
import { isValidJwt, EventBus } from '@/utils'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
const state = {
// single source of data
surveys: [],
currentSurvey: {},
user: {},
jwt: ''
}
},
mutations: {
const actions = {
// asynchronous operations
loadSurveys (context: any) {
return fetchSurveys()
.then((response) => {
context.commit('setSurveys', { surveys: response.data })
})
},
// @ts-ignore
loadSurvey (context: any, { id }) {
return fetchSurvey(id)
.then((response) => {
context.commit('setSurvey', { survey: response.data })
})
},
addSurveyResponse (context: any) {
return saveSurveyResponse(context.state.currentSurvey)
},
actions: {
login (context: any, userData: any) {
context.commit('setUserData', { userData })
return authenticate(userData)
.then(response => context.commit('setJwtToken', { jwt: response.data }))
.catch(error => {
console.log('Error Authenticating: ', error)
// @ts-ignore
EventBus.emit('failedAuthentication', error)
})
},
});
register (context: any, userData: any) {
context.commit('setUserData', { userData })
return register(userData)
.then(context.dispatch('login', userData))
.catch(error => {
console.log('Error Registering: ', error)
// @ts-ignore
EventBus.emit('failedRegistering: ', error)
})
},
submitNewSurvey (context: any, survey: any) {
return postNewSurvey(survey, context.state.jwt.token)
}
}
const mutations = {
// isolated data mutations
setSurveys (state: any, payload: any) {
state.surveys = payload.surveys
},
setSurvey (state: any, payload: any) {
const nQuestions = payload.survey.questions.length
for (let i = 0; i < nQuestions; i++) {
payload.survey.questions[i].choice = null
}
state.currentSurvey = payload.survey
},
setChoice (state: any, payload: any) {
const { questionId, choice } = payload
const nQuestions = state.currentSurvey.questions.length
for (let i = 0; i < nQuestions; i++) {
if (state.currentSurvey.questions[i].id === questionId) {
state.currentSurvey.questions[i].choice = choice
break
}
}
},
setUserData (state: any, payload: any) {
console.log('setUserData payload = ', payload)
state.userData = payload.userData
},
setJwtToken (state: any, payload: any) {
console.log('setJwtToken payload = ', payload)
localStorage.token = payload.jwt.token
state.jwt = payload.jwt
}
}
const getters = {
// reusable data accessors
isAuthenticated (state: any) {
return isValidJwt(state.jwt.token)
}
}
const store = new Vuex.Store({
state,
actions,
mutations,
getters
})
export default store