Created
January 4, 2020 06:52
-
-
Save julianrubisch/48266b933cd6d0126e0efe8ab1856fe0 to your computer and use it in GitHub Desktop.
middleware v1
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
// 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