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 CachedValue and CachedFunction #41

Merged
merged 29 commits into from
Jul 24, 2023
Merged

Add CachedValue and CachedFunction #41

merged 29 commits into from
Jul 24, 2023

Conversation

fregante
Copy link
Owner

@fregante fregante commented May 25, 2023

First pass for:

This new API is supposed to replace the old "Map-like" API and merge it with cache.function.

Simple usage

const choice = new CacheItem<boolean>('choice', {
	maxAge: {days: 30}
});
if (await choice.get() === undefined) {
	await choice.set(confirm('Want some cookies?'))
}

resetCacheButton.addEventListener('click', async () => {
	await choice.delete()
	location.reload()
})

Usage with updater

const email = new CacheItem<boolean>('choice', {
	maxAge: {days: 30},
	updater: async (user: string) => {
		const response = fetch('/api?user=' user);
		return response.text();
	}
});


const user1 = await email.get('koalaman');
const user2 = await email.get('supercat');

if (!await email.getCached('ironbird')) {
	alert('User `ironbird` not in cache')
}

refreshCacheButton.addEventListener('click', async () => {
	await email.getFresh('supercat')
})

Next steps

  • Port old tests to new API
  • Test new APIs (like getCached)
  • Write type tests for new API with vitest
  • Inline old logic in cache-item instead of importing it. Not strictly necessary at this point
  • Move old logic to ./legacy.ts and new to ./index.ts
  • Update readme
  • Write migration guide + how to use the legacy API

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

Typing this is a supreme PITA, so for the sake of types and documentation, I'll probably export two classes:

  • CacheItem
  • DynamicCacheItem (or UpdatableCacheItem)

@fregante fregante changed the title Add CacheItem API Add CachedValue and CachedFunction Jun 8, 2023
@fregante fregante marked this pull request as ready for review July 24, 2023 21:28
@fregante fregante merged commit 5255795 into main Jul 24, 2023
@fregante fregante deleted the cache-item-api branch July 24, 2023 21:30
@fregante fregante linked an issue Jul 24, 2023 that may be closed by this pull request
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 this pull request may close these issues.

Add a get/set helpers to the function cache.function returns
1 participant