Skip to content
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

feat: cache async results #36

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
- Fast and lightweight argument parser based on [mri](https://github.com/lukeed/mri)
- Smart value parsing with typecast, boolean shortcuts and unknown flag handling
- Nested sub-commands
- Lazy and Async commands
- Lazy and Async commands, caching async results
- Plugable and composable API
- Auto generated usage and help

Expand Down
14 changes: 12 additions & 2 deletions src/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,18 @@ export function formatLineColumns(lines: string[][], linePrefix = "") {
.join("\n");
}

export function resolveValue<T>(input: Resolvable<T>): T | Promise<T> {
return typeof input === "function" ? (input as any)() : input;
const cache = new WeakMap<Function, any>();

export async function resolveValue<T>(input: Resolvable<T>): Promise<T> {
if (typeof input === 'function') {
let result: T = cache.get(input);
if (!result) {
result = await (input as any)();
cache.set(input, result);
}
return result;
}
return input;
}

export class CLIError extends Error {
Expand Down