Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Created January 4, 2020 06:54
Show Gist options
  • Save julianrubisch/eae3a1600f1918dea9c48d32c0c10e45 to your computer and use it in GitHub Desktop.
Save julianrubisch/eae3a1600f1918dea9c48d32c0c10e45 to your computer and use it in GitHub Desktop.
middleware v2
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