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: {
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)

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

@ -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("/")
}
}
})

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

@ -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,13 +16,16 @@ export function goToSpeckleAuthPage() {
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(REFRESH_TOKEN)
}
export function exchangeAccessCode(accessCode){
return fetch(`${SERVER_URL}/auth/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',
headers: {
'Content-Type': 'application/json',
@ -32,38 +36,47 @@ 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) {
// 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)
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)")
}
// 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))

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

@ -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)

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

@ -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
}
}
},