import { StorageSharedKeyCredential , BlobServiceClient , SASProtocol , generateBlobSASQueryParameters , BlobSASPermissions , ContainerClient , BlobSASSignatureValues } from "@azure/storage-blob" ; import { STORAGE_ACCOUNT , STORAGE_ACCOUNT_KEY } from "../../util/secrets" ; import { UploadBlobResult } from "../storage.d" ; const sharedKeyCredential = new StorageSharedKeyCredential ( STORAGE_ACCOUNT as string , STORAGE_ACCOUNT_KEY as string ) ; const blobServiceClient = new BlobServiceClient ( `https://${ STORAGE_ACCOUNT }.blob.core.windows.net` , sharedKeyCredential ) ; export const uploadBlob = async ( stream , contentLength , containerName , blobName ) : Promise < UploadBlobResult > => { let existing = false ; for await ( const container of blobServiceClient . listContainers ( ) ) { if ( containerName === container . name ) { existing = true ; break ; } } const containerClient = blobServiceClient . getContainerClient ( containerName ) ; if ( ! existing ) { await containerClient . create ( ) ; } const blobClient = containerClient . getBlobClient ( blobName ) ; const blockBlobClient = blobClient . getBlockBlobClient ( ) ; return blockBlobClient . upload ( ( ) => stream , contentLength ) . then ( ( value ) => { return new Promise < UploadBlobResult > ( ( resolve , reject ) : any => { resolve ( { blobUrl : blockBlobClient . url , statusCode : value . _response . status } as UploadBlobResult ) ; } ) ; } ) . catch ( ( error ) => { return new Promise < UploadBlobResult > ( ( resolve , reject ) : any => { reject ( error . message ) ; } ) ; } ) ; } ; export const generateSigningUrlParams = ( containerName , blobName , neverExpire ? ) : string => { const now = new Date ( ) ; now . setMinutes ( now . getMinutes ( ) - 15 ) ; const blobSASSignatureValues = { containerName : containerName , blobName : blobName , startsOn : now , permissions : BlobSASPermissions . parse ( "r" ) , protocol : SASProtocol . Https , } ; const expiryTime = new Date ( ) ; if ( neverExpire ) { expiryTime . setFullYear ( expiryTime . getFullYear ( ) + 1000 ) ; } else { expiryTime . setDate ( expiryTime . getDate ( ) + 1 ) ; } blobSASSignatureValues . expiresOn = expiryTime ; return generateBlobSASQueryParameters ( blobSASSignatureValues , sharedKeyCredential ) . toString ( ) ; } ;