Skip to content

feat(create-email): caching of fetch to fallback to when fetch fails #2309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mighty-views-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-email": patch
---

caching of versions to use when fetch of latest fails
1 change: 1 addition & 0 deletions packages/create-email/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.test
./.cache
34 changes: 31 additions & 3 deletions packages/create-email/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,38 @@ const packageJson = JSON.parse(
);

const getLatestVersionOfTag = async (packageName, tag) => {
const response = await fetch(
`https://registry.npmjs.org/${packageName}/${tag}`,
const cacheFilename = `${packageName.replaceAll('/', '-')}-${tag}.json`;

const cacheDir = path.join(
path.dirname(fileURLToPath(import.meta.url)),
'..',
'.cache',
);
const data = await response.json();

if (!fse.existsSync(cacheDir)) {
fse.mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
}

const cachePath = path.join(cacheDir, cacheFilename);

let data;
try {
const response = await fetch(
`https://registry.npmjs.org/${packageName}/${tag}`,
);
data = await response.json();

fse.writeFileSync(cachePath, JSON.stringify(data), { mode: 0o600 });
} catch (exception) {
if (fse.existsSync(cachePath)) {
console.warn(
`${logSymbols.warning} Failed to fetch the latest version from npm, using a cache`,
);
data = fse.readJSONSync(cachePath);
} else {
throw exception;
}
}

if (typeof data === 'string' && data.startsWith('version not found')) {
console.error(`Tag ${tag} does not exist for ${packageName}.`);
Expand Down
Loading