From 16997ee63d2314d2bf17103e2d430e1c5dad8373 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20Sch=C3=A4fer?= Date: Wed, 19 Dec 2018 18:02:11 +0100 Subject: [PATCH] Refactor `login` with confidence This is why I :heart: testing. First I wrote several tests to get familiar with the existing code and specified everything that I believe to be required. Then I refactor the entire method at once and the tests pass. Note that I do **not** believe that setting the user data to `null` is really relevant. --- store/auth.js | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/store/auth.js b/store/auth.js index ff60ef849..e3ed9f383 100644 --- a/store/auth.js +++ b/store/auth.js @@ -78,10 +78,8 @@ export const actions = { return getters.isLoggedIn }, async login({ commit }, { email, password }) { + commit('SET_PENDING', true) try { - commit('SET_PENDING', true) - commit('SET_USER', null) - commit('SET_TOKEN', null) const res = await this.app.apolloProvider.defaultClient .mutate({ mutation: gql(` @@ -101,23 +99,15 @@ export const actions = { }) .then(({ data }) => data && data.login) - if (res && res.token) { - await this.app.$apolloHelpers.onLogin(res.token) - commit('SET_TOKEN', res.token) - const userData = Object.assign({}, res) - delete userData.token - commit('SET_USER', userData) - commit('SET_PENDING', false) - return true - } else { - commit('SET_PENDING', false) - throw new Error('THERE IS AN ERROR') - } + await this.app.$apolloHelpers.onLogin(res.token) + commit('SET_TOKEN', res.token) + const userData = Object.assign({}, res) + delete userData.token + commit('SET_USER', userData) } catch (err) { - commit('SET_USER', null) - commit('SET_TOKEN', null) - commit('SET_PENDING', false) throw new Error(err) + } finally { + commit('SET_PENDING', false) } }, async logout({ commit }) {