Merge pull request #3 from specklesystems/alan/cleanup

Cleanup: Removed promises in favour of async/await
This commit is contained in:
Alan Rynne 2021-05-18 13:36:43 +02:00 коммит произвёл GitHub
Родитель 270fc5bd5a 95c4410bf2
Коммит bf6d2bb681
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
5 изменённых файлов: 76 добавлений и 67 удалений

Просмотреть файл

@ -57,12 +57,10 @@ export default {
} }
}, },
methods: { methods: {
fetchSearchResults(e) { async fetchSearchResults(e) {
if (!e || e?.length < 3) return if (!e || e?.length < 3) return
return searchStreams(e) var json = await searchStreams(e)
.then(json => { this.streams = json.data.streams
this.streams = json.data.streams
})
}, },
debounceInput: debounce(function (e) { debounceInput: debounce(function (e) {
this.fetchSearchResults(e) this.fetchSearchResults(e)

Просмотреть файл

@ -21,19 +21,23 @@ const router = new VueRouter({
router.beforeEach( async (to, from, next) => { router.beforeEach( async (to, from, next) => {
if(to.query.access_code){ if(to.query.access_code){
// If the route contains an access code, exchange it and go home. // If the route contains an access code, exchange it
store.dispatch('exchangeAccessCode', to.query.access_code) try {
.then(() => next("/")) await store.dispatch('exchangeAccessCode', to.query.access_code)
.catch(err => { } catch (err){
console.warn("exchange failed", err); console.warn("exchange failed", err);
next("/") }
}) // Whatever happens, go home.
next("/")
} }
else { else {
// Check on every route change if you still have access. try {
store.dispatch("getUser") // Check on every route change if you still have access.
.then(to => next(to)) var goto = await store.dispatch("getUser")
.catch(err => next("/")) next(goto)
} catch (err) {
next("/")
}
} }
}) })

Просмотреть файл

@ -6,6 +6,7 @@ export const TOKEN = `${APP_NAME}.AuthToken`
export const REFRESH_TOKEN = `${APP_NAME}.RefreshToken` export const REFRESH_TOKEN = `${APP_NAME}.RefreshToken`
export const CHALLENGE = `${APP_NAME}.Challenge` 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() { export function goToSpeckleAuthPage() {
// Generate random challenge // Generate random challenge
var challenge = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) var challenge = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
@ -15,13 +16,16 @@ export function goToSpeckleAuthPage() {
window.location = `${SERVER_URL}/authn/verify/${process.env.VUE_APP_SPECKLE_ID}/${challenge}` window.location = `${SERVER_URL}/authn/verify/${process.env.VUE_APP_SPECKLE_ID}/${challenge}`
} }
export function speckleLogOut(){ // 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(TOKEN)
localStorage.removeItem(REFRESH_TOKEN) localStorage.removeItem(REFRESH_TOKEN)
} }
export function exchangeAccessCode(accessCode){ // Exchanges the provided access code with a token/refreshToken pair, and saves them to local storage.
return fetch(`${SERVER_URL}/auth/token/`, { export async function exchangeAccessCode(accessCode) {
var res = await fetch(`${SERVER_URL}/auth/token/`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -32,38 +36,47 @@ export function exchangeAccessCode(accessCode){
appSecret: process.env.VUE_APP_SPECKLE_SECRET, appSecret: process.env.VUE_APP_SPECKLE_SECRET,
challenge: localStorage.getItem(CHALLENGE) 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) {
// 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)
}
return data
} }
export function speckleFetch(query){ // Calls the GraphQL endpoint of the Speckle server with a specific query.
export async function speckleFetch(query) {
let token = localStorage.getItem(TOKEN) let token = localStorage.getItem(TOKEN)
if (token) if (token)
return fetch( try {
`${SERVER_URL}/graphql`, var res = await fetch(
{ `${SERVER_URL}/graphql`,
method: 'POST', {
headers: { method: 'POST',
'Authorization': 'Bearer ' + token, headers: {
'Content-Type': 'application/json' 'Authorization': 'Bearer ' + token,
}, 'Content-Type': 'application/json'
body: JSON.stringify({ },
query: query body: JSON.stringify({
query: query
})
}) })
}) return await res.json()
.then(res => res.json()) } catch (err) {
console.error("API call failed", err)
}
else else
return Promise.reject("You are not logged in (token does not exist)") 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()) export const getUserData = () => speckleFetch(userInfoQuery())
// Fetch for streams matching the specified text using the streamSearchQuery
export const searchStreams = (e) => speckleFetch(streamSearchQuery(e)) 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)) export const getStreamCommits = (streamId, itemsPerPage, cursor) => speckleFetch(streamCommitsQuery(streamId, itemsPerPage, cursor))

Просмотреть файл

@ -70,34 +70,29 @@ export default new Vuex.Store({
// Here, we could save the tokens to the store if necessary. // Here, we could save the tokens to the store if necessary.
return exchangeAccessCode(accessCode) return exchangeAccessCode(accessCode)
}, },
getUser(context) { async getUser(context) {
return getUserData() try {
.then(json => { var json = await getUserData()
var data = json.data var data = json.data
context.commit("setUser", data.user) context.commit("setUser", data.user)
context.commit("setServerInfo", data.serverInfo) context.commit("setServerInfo", data.serverInfo)
}) } catch (err) {
.catch(err => { console.error(err)
console.error(err) }
})
}, },
redirectToAuth() { redirectToAuth() {
goToSpeckleAuthPage() goToSpeckleAuthPage()
}, },
handleStreamSelection(context, stream) { async handleStreamSelection(context, stream) {
context.commit("setCurrentStream", stream) context.commit("setCurrentStream", stream)
context.commit("setTableOptions", { itemsPerPage: 5 }) context.commit("setTableOptions", { itemsPerPage: 5 })
context.commit("resetPrevCursors") context.commit("resetPrevCursors")
return getStreamCommits(stream.id, 5, null) var json = await getStreamCommits(stream.id, 5, null)
.then(json => { context.commit("setCommits", json.data.stream.commits)
context.commit("setCommits", json.data.stream.commits)
})
}, },
getCommits(context, cursor) { async getCommits(context, cursor) {
return getStreamCommits(context.state.currentStream.id, 5, cursor) var json = await getStreamCommits(context.state.currentStream.id, 5, cursor)
.then(json => { context.commit("setCommits", json.data.stream.commits)
context.commit("setCommits", json.data.stream.commits)
})
}, },
clearStreamSelection(context){ clearStreamSelection(context){
context.commit("setCurrentStream", null) context.commit("setCurrentStream", null)

Просмотреть файл

@ -88,22 +88,21 @@ export default {
}, },
watch: { watch: {
options: { options: {
handler(val, oldval) { async handler(val, oldval) {
this.$store.commit("setTableOptions", val) this.$store.commit("setTableOptions", val)
if (oldval.page && val.page != oldval.page) { if (oldval.page && val.page != oldval.page) {
if (val.page > oldval.page) { if (val.page > oldval.page) {
this.loading = true this.loading = true
var cursor = this.$store.state.latestCommits.cursor var cursor = this.$store.state.latestCommits.cursor
this.$store.dispatch("getCommits", cursor).then(() => { await this.$store.dispatch("getCommits", cursor)
this.$store.commit("addCursorToPreviousList", cursor) this.$store.commit("addCursorToPreviousList", cursor)
this.loading = false this.loading = false
})
} else { } else {
console.log("page down") console.log("page down")
this.loading = true this.loading = true
this.$store.dispatch("getCommits", this.previousCursors[val.page - 1]).then(() => { await this.$store.dispatch("getCommits", this.previousCursors[val.page - 1])
this.loading = false this.loading = false
})
} }
} }
}, },