diff --git a/source/session.ts b/source/session.ts index 5ff788b1..a394eb65 100644 --- a/source/session.ts +++ b/source/session.ts @@ -926,6 +926,8 @@ export class Session { * @param {?object} [options = {}] - Options * @param {?string} options.name - Component name. Defaults get from file object. * @param {?number} options.data - Component data. Defaults to {}. + * @param {XMLHttpRequest} options.xhr - Custom XHR object, deprecated in favor of options.signal. + * @param {AbortSignal} options.signal - Abort signal * @return {Promise} Promise resolved with the response when creating * Component and ComponentLocation. */ @@ -949,6 +951,12 @@ export class Session { const defaultProgress = (progress: number) => progress; const defaultAbort = () => {}; + if (options.xhr) { + logger.warn( + "[session.createComponent] options.xhr is deprecated, use options.signal for aborting uploads." + ); + } + const data = options.data || {}; const onProgress = options.onProgress || defaultProgress; const xhr = options.xhr || new XMLHttpRequest(); @@ -962,6 +970,12 @@ export class Session { let url: string; let headers: Record = {}; + const handleAbortSignal = () => { + xhr.abort(); + options.signal?.removeEventListener("abort", handleAbortSignal); + }; + options.signal?.addEventListener("abort", handleAbortSignal); + const updateOnProgressCallback = ( oEvent: ProgressEvent ) => { diff --git a/source/types.ts b/source/types.ts index e8170064..0b28895b 100644 --- a/source/types.ts +++ b/source/types.ts @@ -19,6 +19,7 @@ export interface CreateComponentOptions { data?: Data; onProgress?: (progress: number) => unknown; xhr?: XMLHttpRequest; + signal?: AbortSignal; onAborted?: () => unknown; } diff --git a/test/session.test.js b/test/session.test.js index 14794d50..fe574d7d 100755 --- a/test/session.test.js +++ b/test/session.test.js @@ -289,7 +289,7 @@ describe("Session", () => { }); }); - it("Should support abort of uploading file", async () => { + it("Should support abort of uploading file using xhr", async () => { const data = { foo: "bar" }; const blob = new Blob([JSON.stringify(data)], { type: "application/json", @@ -313,6 +313,30 @@ describe("Session", () => { await expect(promise).resolves.toEqual(true); }); + it("Should support abort of uploading file using signal", async () => { + const data = { foo: "bar" }; + const blob = new Blob([JSON.stringify(data)], { + type: "application/json", + }); + + const controller = new AbortController(); + const promise = new Promise((resolve) => { + const onAborted = () => { + resolve(true); + }; + + session.createComponent(blob, { + signal: controller.signal, + name: "data.json", + onProgress: () => { + controller.abort(); + }, + onAborted, + }); + }); + await expect(promise).resolves.toEqual(true); + }); + it.skip("Should support ensure with create", async () => { const identifyingKeys = ["key", "parent_id", "parent_type"]; const key = uuidV4();