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

Export NewItem function #151

Merged
merged 1 commit into from
Sep 23, 2024
Merged

Export NewItem function #151

merged 1 commit into from
Sep 23, 2024

Conversation

hasfjord
Copy link
Contributor

There might be multiple reasons for creating an Item object manually. Now the only way of creating such an object is to add it to the cache, which might not always be ideal.
My use-case is allowing a workaround for loader error handling.

By storing the error in the value it could be inspected by the caller of the get function.

Cached function:

type cachedValue struct {
	usefulString string
	Err          error
}

Loader:

loader := ttlcache.LoaderFunc[string, *cachedValue](
		func(c *ttlcache.Cache[string, *cachedValue], key string) *ttlcache.Item[string, *cachedValue] {
			v, err := SomethingThatCouldFail()
			if err != nil {
				return ttlcache.NewItem(key, cachedValue{"", err}, 0, false)
			}
			return c.Set(key, v, 1*time.Hour)
		})

Cache setup:

cache := ttlcache.New(
		ttlcache.WithTTL[string, *cachedValue](1*time.Hour),
		ttlcache.WithLoader(loader),
	)

Get call:

// Get the value from the cache
item := cache.Get("key").Value()
if item.Err != nil {
	//handle error
}
// use item.Value().usefulString

I would prefer the loader function returning an error in addition to the error, but that would break the current api contract.

Copy link
Contributor

@swithek swithek left a comment

Choose a reason for hiding this comment

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

I quite like the loader error workaround in your example. There's just one small change that we need to make:

item_test.go Outdated Show resolved Hide resolved
@swithek
Copy link
Contributor

swithek commented Sep 20, 2024

Regarding the loader interface and errors: we have this issue, feel free to upvote it/share your ideas there as well.

Copy link
Contributor

@swithek swithek left a comment

Choose a reason for hiding this comment

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

Thank you for your contribution @hasfjord.

@swithek swithek merged commit 9d01666 into jellydator:v3 Sep 23, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants