Skip to content

Export NewItem function#151

Merged
swithek merged 1 commit intojellydator:v3from
hasfjord:v3
Sep 23, 2024
Merged

Export NewItem function#151
swithek merged 1 commit intojellydator:v3from
hasfjord:v3

Conversation

@hasfjord
Copy link
Copy Markdown
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
Copy Markdown
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:

Comment thread item_test.go Outdated
@swithek
Copy link
Copy Markdown
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
Copy Markdown
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.

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