11import { Readable } from 'node:stream' ;
22import axios from 'axios' ;
33import { UploadOptions } from '../../types/network.types' ;
4+ import { NetworkFacade } from './network-facade.service' ;
45
56export class UploadService {
67 public static readonly instance : UploadService = new UploadService ( ) ;
78
8- async uploadFile ( url : string , from : Readable | Buffer , options : UploadOptions ) : Promise < { etag : string } > {
9+ public uploadFileToNetwork = async (
10+ url : string ,
11+ from : Readable | Buffer ,
12+ options : UploadOptions ,
13+ ) : Promise < { etag : string } > => {
914 const response = await axios . put ( url , from , {
1015 signal : options . abortController ?. signal ,
1116 onUploadProgress : ( progressEvent ) => {
@@ -20,5 +25,44 @@ export class UploadService {
2025 throw new Error ( 'Missing Etag in response when uploading file' ) ;
2126 }
2227 return { etag } ;
23- }
28+ } ;
29+
30+ public uploadFileStream = async (
31+ fileStream : Readable ,
32+ userBucket : string ,
33+ userMnemonic : string ,
34+ fileSize : number ,
35+ networkFacade : NetworkFacade ,
36+ progressCallback ?: ( progress : number ) => void ,
37+ ) => {
38+ const minimumMultipartThreshold = 100 * 1024 * 1024 ;
39+ const useMultipart = fileSize > minimumMultipartThreshold ;
40+ const partSize = 30 * 1024 * 1024 ;
41+ const parts = Math . ceil ( fileSize / partSize ) ;
42+
43+ let uploadOperation : Promise <
44+ [
45+ Promise < {
46+ fileId : string ;
47+ hash : Buffer ;
48+ } > ,
49+ AbortController ,
50+ ]
51+ > ;
52+
53+ if ( useMultipart ) {
54+ uploadOperation = networkFacade . uploadMultipartFromStream ( userBucket , userMnemonic , fileSize , fileStream , {
55+ parts,
56+ progressCallback,
57+ } ) ;
58+ } else {
59+ uploadOperation = networkFacade . uploadFromStream ( userBucket , userMnemonic , fileSize , fileStream , {
60+ progressCallback,
61+ } ) ;
62+ }
63+
64+ const uploadFileOperation = await uploadOperation ;
65+
66+ return uploadFileOperation ;
67+ } ;
2468}
0 commit comments