Big refactor of speckle related stuff into files

This commit is contained in:
Alan Rynne 2021-04-23 11:11:50 +02:00
Родитель b1a4e7f925
Коммит 834d17b33c
8 изменённых файлов: 186 добавлений и 166 удалений

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

@ -1,3 +1,4 @@
VUE_APP_SPECKLE_ID=720cce4c99
VUE_APP_SPECKLE_SECRET=d26ea2c5c0
VUE_APP_SERVER_URL=https://latest.speckle.dev
VUE_APP_SERVER_URL=https://latest.speckle.dev
VUE_APP_SPECKLE_NAME=SpeckleDemo

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

@ -12,6 +12,7 @@ module.exports = {
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-unused-vars': 'off'
}
}

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

@ -39,9 +39,7 @@
<script>
import {debounce} from "debounce"
const TOKEN = 'SpeckleDemo.AuthToken'
const SERVER_URL = process.env.VUE_APP_SERVER_URL
import { searchStreams } from "@/speckleUtils";
export default {
name: "StreamSearch",
@ -60,35 +58,9 @@ export default {
},
methods: {
fetchSearchResults(e) {
if( !e || e?.length < 3) return;
console.log("execute search", e)
let token = localStorage.getItem(TOKEN)
if (token) {
fetch(`${SERVER_URL}/graphql`, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: `
query {
streams(query: "${e}") {
totalCount
cursor
items {
id
name
updatedAt
}
}
}
`,
})
}
)
.then(res => res.json()).then(json => { console.warn(json.data.streams); this.streams = json.data.streams }, this)
}
if( !e || e?.length < 3) return
searchStreams(e)
.then(json => { this.streams = json.data.streams }, this)
},
debounceInput: debounce(function (e) {
this.fetchSearchResults(e)

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

@ -19,17 +19,18 @@ const router = new VueRouter({
routes
})
router.beforeEach( (to, from, next) => {
store.dispatch("getUser").then(() => {
if(to.query.access_code){
console.log("route contains access code...")
return store.dispatch('exchangeAccessCode', to.query.access_code).then(() => "/").catch(err => console.warn("exchange failed", err))
}
}).then(to => next(to))
.catch(err => {
console.warn("get user failed",err)
next("/")
})
router.beforeEach( async (to, from, next) => {
if(to.query.access_code){
console.log("route contains access code...")
store.dispatch('exchangeAccessCode', to.query.access_code).then(() => next("/")).catch(err => console.warn("exchange failed", err))
}
else {
store.dispatch("getUser").then(to => next(to))
.catch(err => {
console.warn("get user failed",err)
next("/")
})
}
})
export default router

39
src/speckleQueries.js Normal file
Просмотреть файл

@ -0,0 +1,39 @@
export const userInfoQuery = () => `query {
user {
name
},
serverInfo {
name
company
}
}`
export const streamCommitsQuery = (streamId, itemsPerPage, cursor) => `query {
stream(id: "${streamId}"){
commits(limit: ${itemsPerPage}, cursor: ${cursor ? '"' + cursor + '"' : null}) {
totalCount
cursor
items{
id
message
branchName
sourceApplication
referencedObject
authorName
createdAt
}
}
}
}`
export const streamSearchQuery = (search) => `query {
streams(query: "${search}") {
totalCount
cursor
items {
id
name
updatedAt
}
}
}`

69
src/speckleUtils.js Normal file
Просмотреть файл

@ -0,0 +1,69 @@
import {streamCommitsQuery, streamSearchQuery, userInfoQuery} from "@/speckleQueries";
export const APP_NAME = process.env.VUE_APP_SPECKLE_NAME
export const SERVER_URL = process.env.VUE_APP_SERVER_URL
export const TOKEN = `${APP_NAME}.AuthToken`
export const REFRESH_TOKEN = `${APP_NAME}.RefreshToken`
export const CHALLENGE = `${APP_NAME}.Challenge`
export function goToSpeckleAuthPage() {
// Generate random challenge
var challenge = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
// Save challenge in localStorage
localStorage.setItem(CHALLENGE, challenge)
// Send user to auth page
window.location = `${SERVER_URL}/authn/verify/${process.env.VUE_APP_SPECKLE_ID}/${challenge}`
}
export function speckleLogOut(){
localStorage.removeItem(TOKEN)
localStorage.removeItem(REFRESH_TOKEN)
}
export function exchangeAccessCode(accessCode){
return fetch(`${SERVER_URL}/auth/token/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
accessCode: accessCode,
appId: 'explorer',
appSecret: 'explorer',
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
})
}
export 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
})
})
.then(res => res.json())
else
return Promise.reject("You are not logged in (token does not exist)")
}
export const getUserData = () => speckleFetch(userInfoQuery())
export const searchStreams = (e) => speckleFetch(streamSearchQuery(e))
export const getStreamCommits = (streamId, itemsPerPage, cursor) => speckleFetch(streamCommitsQuery(streamId, itemsPerPage, cursor))

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

@ -1,23 +1,9 @@
import Vue from 'vue'
import Vuex from 'vuex'
import {exchangeAccessCode, getUserData, goToSpeckleAuthPage, speckleLogOut} from "@/speckleUtils";
Vue.use(Vuex)
const TOKEN = 'SpeckleDemo.AuthToken'
const REFRESH_TOKEN = 'SpeckleDemo.RefreshToken'
const CHALLENGE = 'SpeckleDemo.Challenge'
const SERVER_URL = process.env.VUE_APP_SERVER_URL
const userInfoQuery = `query {
user {
name
},
serverInfo {
name
company
}
}`
export default new Vuex.Store({
state: {
user: null,
@ -48,69 +34,29 @@ export default new Vuex.Store({
context.commit("setServerInfo", null)
context.commit("setToken", null)
context.commit("setRefreshToken", null)
localStorage.removeItem(TOKEN)
localStorage.removeItem(REFRESH_TOKEN)
speckleLogOut()
},
async exchangeAccessCode(context, accessCode) {
let response = await fetch(`${SERVER_URL}/auth/token/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
accessCode: accessCode,
appId: 'explorer',
appSecret: 'explorer',
challenge: localStorage.getItem(CHALLENGE)
})
exchangeAccessCode(context, accessCode) {
return exchangeAccessCode(accessCode).then(data => {
if (data.token) {
context.commit("setToken", data.token)
context.commit("setRefreshToken", data.refreshToken)
}
})
let data = await response.json()
console.log("data", data.token)
if (data.token) {
localStorage.removeItem(CHALLENGE)
context.commit("setToken", data.token)
context.commit("setRefreshToken", data.refreshToken)
localStorage.setItem(TOKEN, data.token)
localStorage.setItem(REFRESH_TOKEN, data.refreshToken)
}
},
getUser(context) {
let token = localStorage.getItem(TOKEN)
if (token) {
fetch(`${SERVER_URL}/graphql`, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
body: JSON.stringify({query: userInfoQuery})
}
)
.then(res => res.json())
.then(json => {
var data = json.data
if (data.user) {
console.log("Got user!", data.user)
context.commit("setUser", data.user)
console.log("User logged in as " + data.user.name)
}
if (data.serverInfo) {
context.commit("setServerInfo", data.serverInfo)
}
})
} else {
console.log("User is not logged in")
}
return getUserData()
.then(json => {
var data = json.data
context.commit("setUser", data.user)
context.commit("setServerInfo", data.serverInfo)
})
.catch(err => {
console.error(err)
})
},
redirectToAuth() {
// Generate random challenge
var challenge = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
// Save challenge in localStorage
localStorage.setItem(CHALLENGE, challenge)
// Send user to auth page
window.location = `${SERVER_URL}/authn/verify/${process.env.VUE_APP_SPECKLE_ID}/${challenge}`
goToSpeckleAuthPage()
}
},
modules: {}

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

@ -10,7 +10,7 @@
<stream-search @selected="streamSelected"/>
</v-col>
</v-row>
<v-row v-if="lastCommitChildren">
<v-row v-if="commits">
<v-col class="d-flex" cols="6" offset="3">
<v-select
v-model="selectedKeys"
@ -21,11 +21,14 @@
></v-select>
</v-col>
</v-row>
<v-row v-if="lastCommitChildren">
<v-row v-if="commits">
<v-col class="d-flex" cols="6" offset="3">
<v-data-table
:loading="loading"
:headers="filteredHeaders"
:items="lastCommitChildren"
:items="commits.items"
:options.sync="options"
:server-items-length="commits.totalCount"
class="elevation-1"
></v-data-table>
</v-col>
@ -38,76 +41,64 @@
<script>
import StreamSearch from "@/components/StreamSearch";
const TOKEN = 'SpeckleDemo.AuthToken'
const SERVER_URL = process.env.VUE_APP_SERVER_URL
import { getStreamCommits} from "@/speckleUtils";
export default {
name: 'Home',
components: {StreamSearch},
data: () => {
return {
loading: false,
options: {
itemsPerPage: 5
},
selectedStream: null,
lastCommitChildren: null,
commits: null,
selectedKeys: ["id", "message"]
}
},
methods: {
streamSelected(stream){
streamSelected(stream) {
console.log("Stream selected", stream)
let token = localStorage.getItem(TOKEN)
if (token)
fetch(
`${SERVER_URL}/graphql`,
{
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: `query {
stream(id: "${stream.id}"){
commits(limit: 10, cursor: null) {
totalCount
cursor
items{
id
message
branchName
sourceApplication
referencedObject
authorName
createdAt
}
}
}
}`
})
this.selectedStream = stream
let ipp = this.options.itemsPerPage
getStreamCommits(stream.id, 10, null)
.then(json => {
console.log("got stream commits", json.data.stream.commits)
this.commits = json.data.stream.commits
})
.then(res => res.json())
.then(json => json.data.stream.commits)
.then(commits => {
console.log("commits", commits)
this.lastCommitChildren = commits.items
})
},
itemsPerPageUpdated(itemsPerPage){
console.log("Items per page updated", itemsPerPage)
},
pageUpdated(page){
console.log("Page updated", page)
}
},
computed: {
availableKeys: function(){
availableKeys: function () {
var keys = {}
this.lastCommitChildren?.forEach(obj => {
this.commits?.items.forEach(obj => {
Object.keys(obj).forEach(key => {
if(!keys[key]){
if (!keys[key]) {
keys[key] = true
}
})
})
return Object.keys(keys)
},
filteredHeaders: function() {
return this.selectedKeys.map(key => { return { text: key, value: key}})
filteredHeaders: function () {
return this.selectedKeys.map(key => {
return {text: key, value: key}
})
}
},
watch: {
options: {
handler() {
console.log('options have changed', this.options)
},
deep: true
}
}
}