Last active
March 7, 2021 10:02
-
-
Save akellbl4/de67d8af61fd34bd6b6555ca76ee9c02 to your computer and use it in GitHub Desktop.
Article: https://itnext.io/fetch-shared-data-in-next-js-with-single-request-833433fa8ed1 Full code: https://github.com/akellbl4/cache-proxy
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 path = require("path"); | |
const crypto = require("crypto"); | |
const fs = require("fs/promises"); | |
const fetch = require("isomorphic-unfetch"); | |
const { API_URL, CACHE_DIR } = process.env; | |
const RESOUCES = ["/posts", "/albums"]; | |
function getFilename(str) { | |
const hash = crypto.createHash("sha1").update(str).digest("hex"); | |
return `${hash}.json`; | |
} | |
function writeResponseToFile(filepath, data) { | |
return fs.writeFile(filepath, data, "utf-8"); | |
} | |
function cacheRequests([endpoint, ...r]) { | |
return new Promise((resolve, reject) => { | |
if (!endpoint) { | |
console.log("\nResources have been succesfully cached 📦"); | |
return resolve(); | |
} | |
const url = `${API_URL}${endpoint}`; | |
const filename = getFilename(endpoint); | |
const filepath = path.resolve(__dirname, CACHE_DIR, filename); | |
fetch(url) | |
.then((r) => r.text()) | |
.then((d) => writeResponseToFile(filepath, d)) | |
.then(() => { | |
console.log(`${endpoint} -> ${filepath} 💾`); | |
cacheRequests(r); | |
}) | |
.catch((e) => reject(e)); | |
}); | |
} | |
cacheRequests(RESOUCES); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment