Skip to content

Commit 5ad3682

Browse files
Address code review feedback: extract cache size constant, avoid double file read
Co-authored-by: dportillo-ixs <[email protected]>
1 parent 7b20346 commit 5ad3682

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

packages/htmldocs/src/utils/get-document-component.tsx

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { RawSourceMap } from "source-map-js";
1818
import logger from "~/lib/logger";
1919

2020
// Build cache to avoid rebuilding unchanged files
21+
const MAX_CACHE_SIZE = 50;
2122
const buildCache = new Map<string, {
2223
documentComponent: any;
2324
documentCss: string | undefined;
@@ -40,9 +41,11 @@ export const getDocumentComponent = async (
4041
const startTime = performance.now();
4142

4243
// Check cache based on file content hash
44+
let fileContent: string | undefined;
45+
let hash: string | undefined;
4346
try {
44-
const fileContent = await fs.promises.readFile(documentPath, 'utf-8');
45-
const hash = crypto.createHash('md5').update(fileContent).digest('hex');
47+
fileContent = await fs.promises.readFile(documentPath, 'utf-8');
48+
hash = crypto.createHash('md5').update(fileContent).digest('hex');
4649

4750
if (buildCache.has(hash)) {
4851
logger.debug(`[getDocumentComponent] Using cached build for ${documentPath}`);
@@ -160,23 +163,18 @@ export const getDocumentComponent = async (
160163
sourceMapToOriginalFile: sourceMapToDocument,
161164
};
162165

163-
// Cache the successful result
164-
try {
165-
const fileContent = await fs.promises.readFile(documentPath, 'utf-8');
166-
const hash = crypto.createHash('md5').update(fileContent).digest('hex');
166+
// Cache the successful result using the hash computed earlier
167+
if (hash) {
167168
buildCache.set(hash, result);
168169

169170
// Limit cache size to prevent memory leaks
170-
if (buildCache.size > 50) {
171+
if (buildCache.size > MAX_CACHE_SIZE) {
171172
const firstKey = buildCache.keys().next().value;
172173
if (firstKey) {
173174
buildCache.delete(firstKey);
174175
}
175176
}
176177
logger.debug(`[getDocumentComponent] Result cached with hash ${hash}`);
177-
} catch (cacheError) {
178-
// If caching fails, still return the result
179-
logger.debug(`[getDocumentComponent] Failed to cache result:`, cacheError);
180178
}
181179

182180
return result;

0 commit comments

Comments
 (0)