refactor: decouple table loading from lookup generation

Extract `loadReferenceTableData` to separate the raw file loading
logic from the primary key lookup construction. This prevents
unnecessary Map creation during reverse reference resolution.
This commit is contained in:
2026-08-06 10:42:10 +08:00
parent 641af7341a
commit 6da2815301
+26 -5
View File
@@ -41,13 +41,11 @@ export function hasNestedReferences(schema: Schema): boolean {
}
}
export function loadReferenceTable(
function loadReferenceTableData(
schema: ReferenceSchema | ReverseReferenceSchema,
refBaseDir: string | undefined,
defaultPrimaryKey: string,
currentFilePath: string | undefined,
): {
lookup: Map<string, Record<string, unknown>>;
refTable: Record<string, unknown>[];
refFilePath: string;
} {
@@ -86,6 +84,30 @@ export function loadReferenceTable(
}
}
return { refTable, refFilePath };
}
/**
* Load a referenced table and build a forward lookup keyed by primary key.
* Only call this when forward resolution is actually needed; the reverse
* path uses `loadReferenceTableData` directly to avoid building a throwaway map.
*/
export function loadReferenceTable(
schema: ReferenceSchema | ReverseReferenceSchema,
refBaseDir: string | undefined,
defaultPrimaryKey: string,
currentFilePath: string | undefined,
): {
lookup: Map<string, Record<string, unknown>>;
refTable: Record<string, unknown>[];
refFilePath: string;
} {
const { refTable, refFilePath } = loadReferenceTableData(
schema,
refBaseDir,
currentFilePath,
);
const lookup = new Map<string, Record<string, unknown>>();
refTable.forEach((row) => {
const pkValue = row[defaultPrimaryKey];
@@ -107,10 +129,9 @@ function getReverseLookup(
defaultPrimaryKey: string,
currentFilePath: string | undefined,
): Map<string, Record<string, unknown>[]> {
const { refTable, refFilePath } = loadReferenceTable(
const { refTable, refFilePath } = loadReferenceTableData(
schema,
refBaseDir,
defaultPrimaryKey,
currentFilePath,
);