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

Add a get/set helpers to the function cache.function returns #40

Closed
fregante opened this issue Feb 22, 2023 · 1 comment · Fixed by #41
Closed

Add a get/set helpers to the function cache.function returns #40

fregante opened this issue Feb 22, 2023 · 1 comment · Fixed by #41
Assignees
Labels
enhancement New feature or request

Comments

@fregante
Copy link
Owner

fregante commented Feb 22, 2023

const getDefault = cache.function('default', calculate);

await getDefault(); // Calls the function if not set

await getDefault.get(); // Only gets the cached value

await getDefault.set(await calculate()); // Only sets the value directly into the cache

// We already have this
await getDefault.fresh(); // Skips the cache if it exists, calls the function

Live examples:

@fregante fregante added the enhancement New feature or request label Feb 22, 2023
@fregante
Copy link
Owner Author

fregante commented Mar 1, 2023

It turns out, I hate this whole module API.

I'll update it to a class so that it's more type-safe:

const file = new CacheItem<string>('file');
await file.get();
await file.set('yolo');
await file.delete();

and I will integrate the getter/updater:

async function curl(url: string) {
  const r = await fetch(url);
  return r.text()
}
const contents = new CacheItem<string>('contents', curl);
await contents.get('https://example.com'); // checks cache, then makes calls curl(url: string)
await contents.getFresh('https://example.com'); // calls curl(url: string) only
await contents.getCached('https://example.com'); // checks cache for `url` only
await contents.set('https://example.com', 'contents'); // skips `curl`, sets cache directly, must match type
await contents.delete('https://example.com'); // delete cached item
await contents.clear(); // clears the entire 'contents' cache

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant