Skip to content

Commit

Permalink
Add better error handling
Browse files Browse the repository at this point in the history
Only call onComplete if all files were successfully uploaded
  • Loading branch information
cesardeazevedo committed Oct 25, 2024
1 parent 1d6aec4 commit 760a6cb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"eslint-plugin-prettier": "^5.2.1",
"globals": "^15.9.0",
"happy-dom": "^15.0.0",
"msw": "^2.5.1",
"prettier": "^3.3.3",
"rollup-plugin-peer-deps-external": "^2.2.4",
"rollup-plugin-visualizer": "^5.12.0",
Expand Down
25 changes: 16 additions & 9 deletions src/extensions/FileUploadExtension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface FileUploadOptions {
onDrop: (currentEditor: Editor, file: File, pos: number) => void
onStart: (currentEditor: Editor) => void
onUpload: (currentEditor: Editor, file: UploadTask) => void
onUploadError: (currentEditor: Editor, file: UploadTask) => void
onComplete: (currentEditor: Editor, files: UploadTask[]) => void
}

Expand Down Expand Up @@ -57,6 +58,7 @@ export const FileUploadExtension = Extension.create<FileUploadOptions>({
onDrop() {},
onStart() {},
onUpload() {},
onUploadError() {},
onComplete() {},
}
},
Expand Down Expand Up @@ -102,12 +104,21 @@ export const FileUploadExtension = Extension.create<FileUploadOptions>({
uploader.selectFiles()
tr.setMeta('selectFiles', null)
} else if (tr.getMeta('uploadFiles')) {
let hasErrors = false
this.storage.files = []
this.options.onStart(this.editor)
for await (const file of uploader.uploadFiles()) {
this.storage.files.push(file)
this.options.onUpload(this.editor, file)
if ('error' in file) {
hasErrors = true
this.options.onUploadError(this.editor, file)
} else {
this.options.onUpload(this.editor, file)
}
}
if (!hasErrors) {
this.options.onComplete(this.editor, this.storage.files)
}
this.options.onComplete(this.editor, this.storage.files)
tr.setMeta('uploadFiles', null)
}
})
Expand Down Expand Up @@ -209,20 +220,16 @@ class Uploader {
} catch (error) {
const msg = error as string
this.onUploadDone(node, { error: msg })
throw new Error(msg as string)
return { error: msg }
}
}

async *uploadFiles() {
const tasks = this.findNodes(false).map(([node, pos]) => {
return this.upload(node, pos)
})
try {
for await (const res of tasks) {
yield res
}
} catch (error) {
console.error(error)
for await (const res of tasks) {
yield res
}
}

Expand Down

0 comments on commit 760a6cb

Please sign in to comment.