import { CloudflareWorkerKV } from "types-cloudflare-worker" ; import { ArrayBufferToString } from "./workerhelpers" ; import * as constants from "../worker/constants" ; export default class FileCore { public static getContentType ( fileName , defaultType = "text/plain" , ct = constants . extensionToContentType ) { let filenamesplit = fileName . split ( '.' ) ; let fileExtension = filenamesplit [ filenamesplit . length - 1 ] ; return ct [ fileExtension ] || defaultType ; } param filePath param KV_NAMESPACE param useCache param requestForCache param customHeaders return { Response } return { null } public static async getFile ( filePath , KV_NAMESPACE , useCache = false , requestForCache = null , customHeaders = { } ) { if ( filePath . startsWith ( "/" ) ) { filePath = filePath . substr ( 1 ) ; } filePath = filePath . replace ( '%20' , ' ' ) ; if ( useCache && requestForCache ) { let _cache = await caches . default . match ( requestForCache ) ; if ( _cache ) { return _cache ; } } let arrayBufferValue = await KV_NAMESPACE . get ( filePath , "arrayBuffer" ) ; if ( arrayBufferValue === null ) { return null ; } customHeaders [ "content-type" ] = this . getContentType ( filePath ) ; customHeaders [ "accept-ranges" ] = "none" ; let _asStr = ArrayBufferToString ( arrayBufferValue ) ; if ( ! _asStr . startsWith ( 'SPLIT_' ) ) { let resp = new Response ( arrayBufferValue , { headers : customHeaders } ) ; if ( useCache && requestForCache ) { await caches . default . put ( requestForCache , resp . clone ( ) ) ; } return resp ; } let { readable , writable } = new TransformStream ( ) ; let numberOfKeys = _asStr . split ( '_' ) [ 1 ] ; this . streamKv ( numberOfKeys , writable , KV_NAMESPACE , filePath ) ; return new Response ( readable , { headers : customHeaders } ) ; } public static async streamKv ( numberOfKeys , writable , KV_NAMESPACE , reqpath ) { let writer = writable . getWriter ( ) ; for ( let i = 0 ; i < numberOfKeys ; ++ i ) { writer . releaseLock ( ) ; let a = await KV_NAMESPACE . get ( `${ reqpath }_${ i }` , "stream" ) ; await a . pipeTo ( writable , { preventClose : true } ) ; writer = writable . getWriter ( ) ; } await writer . close ( ) ; } }