Created
January 4, 2020 06:54
-
-
Save julianrubisch/eae3a1600f1918dea9c48d32c0c10e45 to your computer and use it in GitHub Desktop.
middleware v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function encodeAssetCacheName(contentType, contentLength) { | |
return Buffer.from(`${contentType}:${contentLength}`).toString("base64"); | |
} | |
function decodeAssetCacheName(encodedString) { | |
const decodedFileName = Buffer.from(encodedString, "base64").toString( | |
"ascii" | |
); | |
return decodedFileName.split(":"); | |
} | |
// ... | |
if (fs.existsSync(assetCachePath)) { | |
const firstFile = fs.readdirSync(assetCachePath)[0]; | |
const [contentType, contentLength] = middleWare.decodeAssetCacheName( | |
firstFile | |
); | |
res.locals.contentLength = contentLength; | |
res.locals.contentType = contentType; | |
res.locals.buffer = fs.readFileSync(`${assetCachePath}/${firstFile}`); | |
} else { | |
const blob = await (await fetch(res.locals.fetchUrl)).blob(); | |
const fileName = middleWare.encodeAssetCacheName(blob.type, blob.size); | |
res.locals.buffer = Buffer.from(await blob.arrayBuffer(), "binary"); | |
res.locals.contentType = blob.type; | |
res.locals.contentLength = blob.size; | |
fs.writeFileSync(`${assetCachePath}/${fileName}`, res.locals.buffer); | |
} | |
next(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment