import { isStorageError } from '../lib/errors' import { DownloadResult } from '../lib/types' import StreamDownloadBuilder from './StreamDownloadBuilder' export default class BlobDownloadBuilder implements Promise> { readonly [Symbol.toStringTag]: string = 'BlobDownloadBuilder' private promise: Promise> | null = null constructor( private downloadFn: () => Promise, private shouldThrowOnError: boolean ) {} asStream(): StreamDownloadBuilder { return new StreamDownloadBuilder(this.downloadFn, this.shouldThrowOnError) } then, TResult2 = never>( onfulfilled?: ((value: DownloadResult) => TResult1 | PromiseLike) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null ): Promise { return this.getPromise().then(onfulfilled, onrejected) } catch( onrejected?: ((reason: any) => TResult | PromiseLike) | null ): Promise | TResult> { return this.getPromise().catch(onrejected) } finally(onfinally?: (() => void) | null): Promise> { return this.getPromise().finally(onfinally) } private getPromise(): Promise> { if (!this.promise) { this.promise = this.execute() } return this.promise } private async execute(): Promise> { try { const result = await this.downloadFn() return { data: await result.blob(), error: null, } } catch (error) { if (this.shouldThrowOnError) { throw error } if (isStorageError(error)) { return { data: null, error } } throw error } } }