Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: persistent cache for npm package data
- Loading branch information
Showing
3 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import fs from "node:fs/promises"; | ||
import path from "node:path"; | ||
import crypto from "node:crypto"; | ||
import os from "node:os"; | ||
|
||
const enabled = os.platform() === "linux"; | ||
const cacheRoot = process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), ".cache"); | ||
const cacheDir = path.join(cacheRoot, "npm-pkg-lint"); | ||
|
||
function getFilePath(key: string): string { | ||
const hash = crypto.createHash("md5").update(key).digest("hex"); | ||
const filename = `${hash.slice(0, 2)}/${hash.slice(2)}.json`; | ||
return path.join(cacheDir, filename); | ||
} | ||
|
||
export async function persistentCacheGet(key: string): Promise<unknown | null> { | ||
if (!enabled) { | ||
return null; | ||
} | ||
|
||
const filePath = getFilePath(key); | ||
try { | ||
const content = await fs.readFile(filePath, "utf-8"); | ||
return JSON.parse(content) as unknown; | ||
} catch (err: unknown) { | ||
if (err instanceof Error && "code" in err && err.code === "ENOENT") { | ||
return null; | ||
} | ||
throw err; | ||
} | ||
} | ||
|
||
export async function persistentCacheSet(key: string, data: unknown): Promise<void> { | ||
if (!enabled) { | ||
return; | ||
} | ||
|
||
const filePath = getFilePath(key); | ||
const content = JSON.stringify(data, null, 2); | ||
await fs.mkdir(path.dirname(filePath), { recursive: true }); | ||
await fs.writeFile(filePath, content, "utf-8"); | ||
} |