Skip to content

Clean up makeGraph.makeGetter #1167

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

Closed
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
34 changes: 16 additions & 18 deletions src/util/makeGraph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,24 @@ function makeGetter<GraphType, K extends keyof GraphType>(
key: K,
): () => GraphType[K] {
return () => {
let returnValue: GraphType[K];

if (components[key] == null) {
if (lockedKeys.includes(key)) {
const cycle = [...lockedKeys.slice(lockedKeys.indexOf(key)), key].join(
" -> ",
);
throw new Error(`Dependency injection graph cycle detected: ${cycle}`);
}
const factory = factoryMap[key] as (graph: GraphType) => GraphType[K];
lockedKeys.push(key);
returnValue = factory(graph);
if (lockedKeys.pop() !== key) {
throw new Error("Unexpected key at top of graph stack");
}
components[key] = returnValue;
} else {
returnValue = components[key] as GraphType[K];
const componentValue = components[key];
if (componentValue != null) {
return componentValue;
Comment on lines +15 to +17
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If TypeScript is updated we should be able to still check components[key] without an intermediate const: https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#control-flow-analysis-for-element-access

Suggested change
const componentValue = components[key];
if (componentValue != null) {
return componentValue;
if (components[key] != null) {
return components[key];

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice. Fwiw I'll prob just close this PR tho. I factored it out of another PR, but we're moving to pure DI, so this code is all going to go away

}

if (lockedKeys.includes(key)) {
const cycle = [...lockedKeys.slice(lockedKeys.indexOf(key)), key].join(
" -> ",
);
throw new Error(`Dependency injection graph cycle detected: ${cycle}`);
}
const factory = factoryMap[key];
lockedKeys.push(key);
const returnValue = factory(graph);
if (lockedKeys.pop() !== key)˜ {
throw new Error("Unexpected key at top of graph stack");
}
components[key] = returnValue;
return returnValue;
};
}
Expand Down