Skip to content

Commit

Permalink
refactor: async/await across the code
Browse files Browse the repository at this point in the history
Signed-off-by: Pedro Lamas <[email protected]>
  • Loading branch information
pedrolamas committed May 24, 2024
1 parent e24805a commit c5354b5
Show file tree
Hide file tree
Showing 9 changed files with 346 additions and 334 deletions.
17 changes: 8 additions & 9 deletions src/components/common/SystemPrinters.vue
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator'
import type { InitConfig, InstanceConfig } from '@/store/config/types'
import type { InstanceConfig } from '@/store/config/types'
import StateMixin from '@/mixins/state'
import { appInit } from '@/init'
Expand Down Expand Up @@ -84,21 +84,20 @@ export default class SystemPrinters extends Mixins(StateMixin) {
this.instanceDialogOpen = true
}
activateInstance (instance: InstanceConfig) {
async activateInstance (instance: InstanceConfig) {
// Close the drawer
this.$emit('click')
if (!instance.active) {
// Close the socket.
this.$socket.close()
// Re-init the app.
appInit(instance, this.$store.state.config.hostConfig)
.then((config: InitConfig) => {
// Reconnect the socket with the new instance url.
if (config.apiConfig.socketUrl && config.apiConnected && config.apiAuthenticated) {
this.$socket.connect(config.apiConfig.socketUrl)
}
})
const config = await appInit(instance, this.$store.state.config.hostConfig)
// Reconnect the socket with the new instance url.
if (config.apiConfig.socketUrl && config.apiConnected && config.apiAuthenticated) {
this.$socket.connect(config.apiConfig.socketUrl)
}
}
}
}
Expand Down
112 changes: 57 additions & 55 deletions src/components/widgets/filesystem/FileSystem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ import FilePreviewDialog from './FilePreviewDialog.vue'
import type { AppTableHeader, FileWithPath } from '@/types'
import { getFilesFromDataTransfer, hasFilesInDataTransfer } from '@/util/file-system-entry'
import { getFileDataTransferDataFromDataTransfer, hasFileDataTransferTypeInDataTransfer, setFileDataTransferDataInDataTransfer } from '@/util/file-data-transfer'
import consola from 'consola'
/**
* Represents the filesystem, bound to moonrakers supplied roots.
Expand Down Expand Up @@ -637,69 +638,70 @@ export default class FileSystem extends Mixins(StateMixin, FilesMixin, ServicesM
this.goToFileDialogOpen = true
}
handleFileOpenDialog (file: AppFile, mode: 'edit' | 'view' | undefined = undefined) {
const viewOnly = mode
? mode === 'view'
: this.rootProperties.canView.includes(`.${file.extension}`)
async handleFileOpenDialog (file: AppFile, mode: 'edit' | 'view' | undefined = undefined) {
try {
const viewOnly = mode
? mode === 'view'
: this.rootProperties.canView.includes(`.${file.extension}`)
// Grab the file. This should provide a dialog.
const response = await this.getFile(
file.filename,
this.currentPath,
file.size,
{
responseType: viewOnly ? 'arraybuffer' : 'text',
transformResponse: [v => v]
}
)
// Grab the file. This should provide a dialog.
this.getFile(
file.filename,
this.currentPath,
file.size,
{
responseType: viewOnly ? 'arraybuffer' : 'text',
transformResponse: [v => v]
}
)
.then(response => {
if (viewOnly) {
// Open the file preview dialog.
const type = response.headers['content-type']
const blob = new Blob([response.data], { type })
this.filePreviewState = {
open: true,
file,
filename: file.filename,
extension: file.extension,
src: URL.createObjectURL(blob),
type,
readonly: file.permissions === 'r' || this.rootProperties.readonly
}
} else {
// Open the edit dialog.
this.fileEditorDialogState = {
open: true,
contents: response.data,
filename: file.filename,
loading: false,
readonly: file.permissions === 'r' || this.rootProperties.readonly
}
if (viewOnly) {
// Open the file preview dialog.
const type = response.headers['content-type']
const blob = new Blob([response.data], { type })
this.filePreviewState = {
open: true,
file,
filename: file.filename,
extension: file.extension,
src: URL.createObjectURL(blob),
type,
readonly: file.permissions === 'r' || this.rootProperties.readonly
}
})
.finally(() => this.$store.dispatch('files/removeFileDownload'))
.catch(e => e)
} else {
// Open the edit dialog.
this.fileEditorDialogState = {
open: true,
contents: response.data,
filename: file.filename,
loading: false,
readonly: file.permissions === 'r' || this.rootProperties.readonly
}
}
} catch (error: unknown) {
consola.error('[FileSystem] open file', error)
}
}
async handlePreviewGcode (file: AppFile | AppFileWithMeta) {
this.getGcode(file)
.then(response => response?.data)
.then(gcode => {
if (!gcode) return
try {
const response = await this.getGcode(file)
if (this.$router.currentRoute.path !== '/' || !this.$store.getters['layout/isEnabledInCurrentLayout']('gcode-preview-card')) {
this.$router.push({ path: '/preview' })
}
const gcode = response?.data
this.$store.dispatch('gcodePreview/loadGcode', {
file,
gcode
})
})
.catch(e => e)
.finally(() => {
this.$store.dispatch('files/removeFileDownload')
if (!gcode) return
if (this.$router.currentRoute.path !== '/' || !this.$store.getters['layout/isEnabledInCurrentLayout']('gcode-preview-card')) {
this.$router.push({ path: '/preview' })
}
this.$store.dispatch('gcodePreview/loadGcode', {
file,
gcode
})
} catch (error: unknown) {
consola.error('[FileSystem] preview gcode', error)
}
}
handleRefreshMetadata (file: AppFileWithMeta) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,6 @@ export default class FileSystemDownloadDialog extends Mixins(StateMixin) {
handleCancelDownload () {
this.currentDownload?.abortController.abort()
this.$store.dispatch('files/removeFileDownload')
}
}
</script>
27 changes: 14 additions & 13 deletions src/components/widgets/gcode-preview/GcodePreviewCard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ import GcodePreviewParserProgressDialog from './GcodePreviewParserProgressDialog
import type { AppFile } from '@/store/files/types'
import type { MinMax } from '@/store/gcodePreview/types'
import { getFileDataTransferDataFromDataTransfer, hasFileDataTransferTypeInDataTransfer } from '@/util/file-data-transfer'
import consola from 'consola'
@Component({
components: {
Expand Down Expand Up @@ -332,20 +333,20 @@ export default class GcodePreviewCard extends Mixins(StateMixin, FilesMixin, Bro
}
async loadFile (file: AppFile) {
this.getGcode(file)
.then(response => response?.data)
.then(gcode => {
if (!gcode) return
this.$store.dispatch('gcodePreview/loadGcode', {
file,
gcode
})
})
.catch(e => e)
.finally(() => {
this.$store.dispatch('files/removeFileDownload')
try {
const response = await this.getGcode(file)
const gcode = response?.data
if (!gcode) return
this.$store.dispatch('gcodePreview/loadGcode', {
file,
gcode
})
} catch (error: unknown) {
consola.error('[GcodePreview] load', error)
}
}
get printerFile (): AppFile | undefined {
Expand Down
137 changes: 69 additions & 68 deletions src/mixins/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Component } from 'vue-property-decorator'
import type { AxiosRequestConfig, AxiosProgressEvent } from 'axios'
import { httpClientActions } from '@/api/httpClientActions'
import type { FileWithPath } from '@/types'
import consola from 'consola'

@Component
export default class FilesMixin extends Vue {
Expand Down Expand Up @@ -73,45 +74,48 @@ export default class FilesMixin extends Vue {
// Sort out the filepath
const filepath = path ? `${path}/${filename}` : filename

const abortController = new AbortController()

// Add an entry to vuex indicating we're downloading a file.
this.$store.dispatch('files/updateFileDownload', {
filepath,
size,
loaded: 0,
percent: 0,
speed: 0,
abortController
})

// Append any additional options.
const o = {
...options,
signal: abortController.signal,
onDownloadProgress: (event: AxiosProgressEvent) => {
const progress = event.progress ?? (
size > 0
? event.loaded / size
: 0
)

const payload: any = {
filepath,
loaded: event.loaded,
percent: Math.round(progress * 100),
speed: event.rate ?? 0
}
try {
const abortController = new AbortController()

if (event.total) {
size = payload.size = event.total
// Add an entry to vuex indicating we're downloading a file.
this.$store.dispatch('files/updateFileDownload', {
filepath,
size,
loaded: 0,
percent: 0,
speed: 0,
abortController
})

const response = await httpClientActions.serverFilesGet<T>(filepath, {
...options,
signal: abortController.signal,
onDownloadProgress: (event: AxiosProgressEvent) => {
const progress = event.progress ?? (
size > 0
? event.loaded / size
: 0
)

const payload: any = {
filepath,
loaded: event.loaded,
percent: Math.round(progress * 100),
speed: event.rate ?? 0
}

if (event.total) {
size = payload.size = event.total
}

this.$store.dispatch('files/updateFileDownload', payload)
}
})

this.$store.dispatch('files/updateFileDownload', payload)
}
return response
} finally {
this.$store.dispatch('files/removeFileDownload')
}

return await httpClientActions.serverFilesGet<T>(filepath, o)
}

/**
Expand Down Expand Up @@ -171,39 +175,36 @@ export default class FilesMixin extends Vue {
? `${path}/${file.name}`
: file.name

const abortController = new AbortController()

this.$store.dispatch('files/updateFileUpload', {
filepath,
size: file.size,
loaded: 0,
percent: 0,
speed: 0,
cancelled: false,
abortController
})

return httpClientActions.serverFilesUploadPost(file, path, root, andPrint, {
...options,
signal: abortController.signal,
onUploadProgress: (event: AxiosProgressEvent) => {
this.$store.dispatch('files/updateFileUpload', {
filepath,
loaded: event.loaded,
percent: event.progress ? Math.round(event.progress * 100) : 0,
speed: event.rate ?? 0
})
}
})
.then((response) => {
return response
})
.catch(e => {
return e
try {
const abortController = new AbortController()

this.$store.dispatch('files/updateFileUpload', {
filepath,
size: file.size,
loaded: 0,
percent: 0,
speed: 0,
cancelled: false,
abortController
})
.finally(() => {
this.$store.dispatch('files/removeFileUpload', filepath)

const response = await httpClientActions.serverFilesUploadPost(file, path, root, andPrint, {
...options,
signal: abortController.signal,
onUploadProgress: (event: AxiosProgressEvent) => {
this.$store.dispatch('files/updateFileUpload', {
filepath,
loaded: event.loaded,
percent: event.progress ? Math.round(event.progress * 100) : 0,
speed: event.rate ?? 0
})
}
})

return response
} finally {
this.$store.dispatch('files/removeFileUpload', filepath)
}
}

getFullPathAndFile (rootPath: string, file: File | FileWithPath): [string, File] {
Expand Down Expand Up @@ -259,8 +260,8 @@ export default class FilesMixin extends Vue {
if (fileState && !fileState?.cancelled) {
try {
await this.uploadFile(fileObject, fullPath, root, andPrint)
} catch (e) {
return e
} catch (error: unknown) {
consola.error('[FileUpload] file', error)
}
} else {
this.$store.dispatch('files/removeFileUpload', filepath)
Expand Down
Loading

0 comments on commit c5354b5

Please sign in to comment.