From a8a9145846f6aa536f7e022471936450c20236a2 Mon Sep 17 00:00:00 2001 From: Alan Rynne Date: Tue, 18 May 2021 13:03:31 +0200 Subject: [PATCH 1/2] cleanup: Removed all promises in favour of async/await --- src/components/StreamSearch.vue | 8 ++---- src/router/index.js | 26 +++++++++-------- src/speckleUtils.js | 50 ++++++++++++++++++--------------- src/store/index.js | 35 ++++++++++------------- src/views/Home.vue | 15 +++++----- 5 files changed, 67 insertions(+), 67 deletions(-) diff --git a/src/components/StreamSearch.vue b/src/components/StreamSearch.vue index d557eb9..1198d8f 100644 --- a/src/components/StreamSearch.vue +++ b/src/components/StreamSearch.vue @@ -57,12 +57,10 @@ export default { } }, methods: { - fetchSearchResults(e) { + async fetchSearchResults(e) { if (!e || e?.length < 3) return - return searchStreams(e) - .then(json => { - this.streams = json.data.streams - }) + var json = await searchStreams(e) + this.streams = json.data.streams }, debounceInput: debounce(function (e) { this.fetchSearchResults(e) diff --git a/src/router/index.js b/src/router/index.js index 8de77aa..941bd91 100644 --- a/src/router/index.js +++ b/src/router/index.js @@ -21,19 +21,23 @@ const router = new VueRouter({ router.beforeEach( async (to, from, next) => { if(to.query.access_code){ - // If the route contains an access code, exchange it and go home. - store.dispatch('exchangeAccessCode', to.query.access_code) - .then(() => next("/")) - .catch(err => { - console.warn("exchange failed", err); - next("/") - }) + // If the route contains an access code, exchange it + try { + await store.dispatch('exchangeAccessCode', to.query.access_code) + } catch (err){ + console.warn("exchange failed", err); + } + // Whatever happens, go home. + next("/") } else { - // Check on every route change if you still have access. - store.dispatch("getUser") - .then(to => next(to)) - .catch(err => next("/")) + try { + // Check on every route change if you still have access. + var goto = await store.dispatch("getUser") + next(goto) + } catch (err) { + next("/") + } } }) diff --git a/src/speckleUtils.js b/src/speckleUtils.js index 2637110..21ae785 100644 --- a/src/speckleUtils.js +++ b/src/speckleUtils.js @@ -15,13 +15,13 @@ export function goToSpeckleAuthPage() { window.location = `${SERVER_URL}/authn/verify/${process.env.VUE_APP_SPECKLE_ID}/${challenge}` } -export function speckleLogOut(){ +export function speckleLogOut() { localStorage.removeItem(TOKEN) localStorage.removeItem(REFRESH_TOKEN) } -export function exchangeAccessCode(accessCode){ - return fetch(`${SERVER_URL}/auth/token/`, { +export async function exchangeAccessCode(accessCode) { + var res = await fetch(`${SERVER_URL}/auth/token/`, { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -32,32 +32,36 @@ export function exchangeAccessCode(accessCode){ appSecret: process.env.VUE_APP_SPECKLE_SECRET, challenge: localStorage.getItem(CHALLENGE) }) - }).then(res => res.json()).then(data => { - if (data.token) { - localStorage.removeItem(CHALLENGE) - localStorage.setItem(TOKEN, data.token) - localStorage.setItem(REFRESH_TOKEN, data.refreshToken) - } - return data }) + var data = await res.json() + if (data.token) { + localStorage.removeItem(CHALLENGE) + localStorage.setItem(TOKEN, data.token) + localStorage.setItem(REFRESH_TOKEN, data.refreshToken) + } + return data } -export function speckleFetch(query){ +export async function speckleFetch(query) { let token = localStorage.getItem(TOKEN) if (token) - return fetch( - `${SERVER_URL}/graphql`, - { - method: 'POST', - headers: { - 'Authorization': 'Bearer ' + token, - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - query: query + try { + var res = await fetch( + `${SERVER_URL}/graphql`, + { + method: 'POST', + headers: { + 'Authorization': 'Bearer ' + token, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + query: query + }) }) - }) - .then(res => res.json()) + return await res.json() + } catch (err) { + console.error("API call failed", err) + } else return Promise.reject("You are not logged in (token does not exist)") } diff --git a/src/store/index.js b/src/store/index.js index 79d3518..82ad763 100644 --- a/src/store/index.js +++ b/src/store/index.js @@ -70,34 +70,29 @@ export default new Vuex.Store({ // Here, we could save the tokens to the store if necessary. return exchangeAccessCode(accessCode) }, - getUser(context) { - return getUserData() - .then(json => { - var data = json.data - context.commit("setUser", data.user) - context.commit("setServerInfo", data.serverInfo) - }) - .catch(err => { - console.error(err) - }) + async getUser(context) { + try { + var json = await getUserData() + var data = json.data + context.commit("setUser", data.user) + context.commit("setServerInfo", data.serverInfo) + } catch (err) { + console.error(err) + } }, redirectToAuth() { goToSpeckleAuthPage() }, - handleStreamSelection(context, stream) { + async handleStreamSelection(context, stream) { context.commit("setCurrentStream", stream) context.commit("setTableOptions", { itemsPerPage: 5 }) context.commit("resetPrevCursors") - return getStreamCommits(stream.id, 5, null) - .then(json => { - context.commit("setCommits", json.data.stream.commits) - }) + var json = await getStreamCommits(stream.id, 5, null) + context.commit("setCommits", json.data.stream.commits) }, - getCommits(context, cursor) { - return getStreamCommits(context.state.currentStream.id, 5, cursor) - .then(json => { - context.commit("setCommits", json.data.stream.commits) - }) + async getCommits(context, cursor) { + var json = await getStreamCommits(context.state.currentStream.id, 5, cursor) + context.commit("setCommits", json.data.stream.commits) }, clearStreamSelection(context){ context.commit("setCurrentStream", null) diff --git a/src/views/Home.vue b/src/views/Home.vue index 69a9418..92ad5a5 100644 --- a/src/views/Home.vue +++ b/src/views/Home.vue @@ -88,22 +88,21 @@ export default { }, watch: { options: { - handler(val, oldval) { + async handler(val, oldval) { this.$store.commit("setTableOptions", val) if (oldval.page && val.page != oldval.page) { if (val.page > oldval.page) { this.loading = true var cursor = this.$store.state.latestCommits.cursor - this.$store.dispatch("getCommits", cursor).then(() => { - this.$store.commit("addCursorToPreviousList", cursor) - this.loading = false - }) + await this.$store.dispatch("getCommits", cursor) + this.$store.commit("addCursorToPreviousList", cursor) + this.loading = false + } else { console.log("page down") this.loading = true - this.$store.dispatch("getCommits", this.previousCursors[val.page - 1]).then(() => { - this.loading = false - }) + await this.$store.dispatch("getCommits", this.previousCursors[val.page - 1]) + this.loading = false } } }, From 95c4410bf27c5300765685cafd14b4cfa558da9a Mon Sep 17 00:00:00 2001 From: Alan Rynne Date: Tue, 18 May 2021 13:23:24 +0200 Subject: [PATCH 2/2] cleanup: Added minor comments in speckleUtils.js --- src/speckleUtils.js | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/speckleUtils.js b/src/speckleUtils.js index 21ae785..7935578 100644 --- a/src/speckleUtils.js +++ b/src/speckleUtils.js @@ -6,6 +6,7 @@ export const TOKEN = `${APP_NAME}.AuthToken` export const REFRESH_TOKEN = `${APP_NAME}.RefreshToken` export const CHALLENGE = `${APP_NAME}.Challenge` +// Redirects to the Speckle server authentication page, using a randomly generated challenge. Challenge will be stored to compare with when exchanging the access code. export function goToSpeckleAuthPage() { // Generate random challenge var challenge = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) @@ -15,11 +16,14 @@ export function goToSpeckleAuthPage() { window.location = `${SERVER_URL}/authn/verify/${process.env.VUE_APP_SPECKLE_ID}/${challenge}` } +// Log out the current user. This removes the token/refreshToken pair. export function speckleLogOut() { + // Remove both token and refreshToken from localStorage localStorage.removeItem(TOKEN) localStorage.removeItem(REFRESH_TOKEN) } +// Exchanges the provided access code with a token/refreshToken pair, and saves them to local storage. export async function exchangeAccessCode(accessCode) { var res = await fetch(`${SERVER_URL}/auth/token/`, { method: 'POST', @@ -35,6 +39,7 @@ export async function exchangeAccessCode(accessCode) { }) var data = await res.json() if (data.token) { + // If retrieving the token was successful, remove challenge and set the new token and refresh token localStorage.removeItem(CHALLENGE) localStorage.setItem(TOKEN, data.token) localStorage.setItem(REFRESH_TOKEN, data.refreshToken) @@ -42,6 +47,7 @@ export async function exchangeAccessCode(accessCode) { return data } +// Calls the GraphQL endpoint of the Speckle server with a specific query. export async function speckleFetch(query) { let token = localStorage.getItem(TOKEN) if (token) @@ -66,8 +72,11 @@ export async function speckleFetch(query) { return Promise.reject("You are not logged in (token does not exist)") } +// Fetch the current user data using the userInfoQuery export const getUserData = () => speckleFetch(userInfoQuery()) +// Fetch for streams matching the specified text using the streamSearchQuery export const searchStreams = (e) => speckleFetch(streamSearchQuery(e)) +// Get commits related to a specific stream, allows for pagination by passing a cursor export const getStreamCommits = (streamId, itemsPerPage, cursor) => speckleFetch(streamCommitsQuery(streamId, itemsPerPage, cursor)) \ No newline at end of file