import { isStorageError } from '../lib/common/errors' import { DownloadResult } from '../lib/types' export default class StreamDownloadBuilder implements Promise> { readonly [Symbol.toStringTag]: string = 'StreamDownloadBuilder' private promise: Promise> | null = null constructor( private downloadFn: () => Promise, private shouldThrowOnError: boolean ) {} 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: result.body as ReadableStream, error: null, } } catch (error) { if (this.shouldThrowOnError) { throw error } if (isStorageError(error)) { return { data: null, error } } throw error } } }