Skip to content

Commit

Permalink
cache cli version check
Browse files Browse the repository at this point in the history
  • Loading branch information
souporserious committed Apr 18, 2024
1 parent 7af2f21 commit 4be36bc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/nervous-cobras-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-mdxts": patch
---

Save version check to local cache.
16 changes: 8 additions & 8 deletions packages/create-mdxts/src/get-package-version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ if (!existsSync(cacheDirectory)) {
}

/** Fetches the latest version of a package from the NPM registry. */
export async function fetchPackageVersion(packageName: string) {
export async function fetchPackageVersion(
packageName: string
): Promise<string> {
const controller = new AbortController()
const signal = controller.signal
const timeoutId = setTimeout(() => controller.abort(), 2500)
Expand Down Expand Up @@ -45,27 +47,25 @@ function saveVersionToCache(version: string) {
}

function getVersionFromCache() {
if (existsSync(cacheFilePath)) {
const cacheContent = JSON.parse(readFileSync(cacheFilePath, 'utf-8'))
return cacheContent
}
return null
const cacheContent = JSON.parse(readFileSync(cacheFilePath, 'utf-8'))
return cacheContent as { version: string; cachedAt: number }
}

function shouldRefreshCache() {
const cacheContent = getVersionFromCache()
if (!cacheContent) {
return true
}
const DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000
const now = Date.now()
return now - cacheContent.cachedAt > DAY_IN_MILLISECONDS
const FIVE_MINUTES = 5 * 60 * 1000
return now - cacheContent.cachedAt > FIVE_MINUTES
}

/** Fetches the latest version of a package from the NPM registry and caches it. */
export async function getPackageVersion(packageName: string) {
if (shouldRefreshCache()) {
const version = await fetchPackageVersion(packageName)
saveVersionToCache(version)
return version
} else {
const cacheContent = getVersionFromCache()
Expand Down

0 comments on commit 4be36bc

Please sign in to comment.