Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Created January 4, 2020 06:52
Show Gist options
  • Save julianrubisch/48266b933cd6d0126e0efe8ab1856fe0 to your computer and use it in GitHub Desktop.
Save julianrubisch/48266b933cd6d0126e0efe8ab1856fe0 to your computer and use it in GitHub Desktop.
middleware v1
// const cachedAssetPath = ...
try {
if (fs.existsSync(cachedAssetPath)) {
const response = await fetch(res.locals.fetchUrl, { method: "HEAD" });
res.locals.contentLength = response.headers.get("content-length");
res.locals.contentType = response.headers.get("content-type");
res.locals.buffer = fs.readFileSync(cachedAssetPath);
} else {
const blob = await (await fetch(res.locals.fetchUrl)).blob();
res.locals.buffer = Buffer.from(await blob.arrayBuffer(), "binary");
res.locals.contentType = blob.type;
res.localscontentLength = blob.size;
fs.writeFileSync(cachedAssetPath, res.locals.buffer);
}
next();
} catch (e) {
// in case fs.writeFileSync writes partial data and fails
if (fs.existsSync(cachedAssetPath)) {
fs.unlinkSync(cachedAssetPath);
}
res.status(500).send(e.message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment