@@ -42,6 +42,17 @@ function makeAssetCachePath(cacheDir, cacheKey) {
42
42
} ;
43
43
}
44
44
45
+ function encodeAssetCacheName ( contentType , contentLength ) {
46
+ return Buffer . from ( `${ contentType } :${ contentLength } ` ) . toString ( "base64" ) ;
47
+ }
48
+
49
+ function decodeAssetCacheName ( encodedString ) {
50
+ const decodedFileName = Buffer . from ( encodedString , "base64" ) . toString (
51
+ "ascii"
52
+ ) ;
53
+ return decodedFileName . split ( ":" ) ;
54
+ }
55
+
45
56
const middleWare = ( module . exports = function ( options ) {
46
57
return async function ( req , res , next ) {
47
58
options = options || { } ;
@@ -62,27 +73,36 @@ const middleWare = (module.exports = function(options) {
62
73
middleWare . makeDirIfNotExists ( path . join ( options . cacheDir , dir1 , dir2 ) ) ;
63
74
64
75
if ( fs . existsSync ( assetCachePath ) ) {
65
- const response = await fetch ( res . locals . fetchUrl , { method : "HEAD" } ) ;
66
-
67
- res . locals . contentLength = response . headers . get ( "content-length" ) ;
68
- res . locals . contentType = response . headers . get ( "content-type" ) ;
76
+ const firstFile = fs . readdirSync ( assetCachePath ) [ 0 ] ;
69
77
70
78
if ( options . logger )
71
- options . logger . debug ( `Reading buffer from path ${ assetCachePath } ` ) ;
79
+ options . logger . debug (
80
+ `Reading buffer from path ${ assetCachePath } /${ firstFile } `
81
+ ) ;
82
+
83
+ const [ contentType , contentLength ] = middleWare . decodeAssetCacheName (
84
+ firstFile
85
+ ) ;
86
+
87
+ res . locals . contentLength = contentLength ;
88
+ res . locals . contentType = contentType ;
72
89
73
- res . locals . buffer = fs . readFileSync ( assetCachePath ) ;
90
+ res . locals . buffer = fs . readFileSync ( ` ${ assetCachePath } / ${ firstFile } ` ) ;
74
91
} else {
75
92
const blob = await ( await fetch ( res . locals . fetchUrl ) ) . blob ( ) ;
76
93
94
+ const fileName = middleWare . encodeAssetCacheName ( blob . type , blob . size ) ;
77
95
if ( options . logger )
78
- options . logger . debug ( `Writing buffer to path ${ assetCachePath } ` ) ;
96
+ options . logger . debug (
97
+ `Writing buffer to path ${ assetCachePath } /${ fileName } `
98
+ ) ;
79
99
80
100
res . locals . buffer = Buffer . from ( await blob . arrayBuffer ( ) , "binary" ) ;
81
101
82
102
res . locals . contentType = blob . type ;
83
103
res . locals . contentLength = blob . size ;
84
104
85
- fs . writeFileSync ( assetCachePath , res . locals . buffer ) ;
105
+ fs . writeFileSync ( ` ${ assetCachePath } / ${ fileName } ` , res . locals . buffer ) ;
86
106
}
87
107
88
108
next ( ) ;
@@ -105,3 +125,5 @@ const middleWare = (module.exports = function(options) {
105
125
106
126
middleWare . makeAssetCachePath = makeAssetCachePath ;
107
127
middleWare . makeDirIfNotExists = makeDirIfNotExists ;
128
+ middleWare . encodeAssetCacheName = encodeAssetCacheName ;
129
+ middleWare . decodeAssetCacheName = decodeAssetCacheName ;
0 commit comments