cache icon indicating copy to clipboard operation
cache copied to clipboard

Add cacheable function to skip be cached

Open zacscoding opened this issue 3 years ago • 2 comments

Add cacheable function to determine be cached or not.

Hello guys :) I want to determine the Value in Item be cache or not depends on state. For example, Sets the value if not empty, otherwise skip to be cache.

	var items []*MyItems
	err := mycache.Once(&Item{
		Key: "mykey",
		Value: &items,
		Do: func(item *Item) (interface{}, error) {
			// read from database
		},
		Cacheable: func(v interface{}) bool {
			items, ok := v.(*[]*MyItems)
			if !ok {
				return true
			}
			return len(*items) != 0
		},
	})

If you have any better ideas, please leave a comment :). thx!

zacscoding avatar Oct 07 '21 15:10 zacscoding

Hello,

The API could be simpler, for example, you can return an error to indicate that the item should not be cached

if len(items) == 0 {
    return nil, cache.ErrNoCache
}

What do you think?

vmihailenco avatar Oct 12 '21 12:10 vmihailenco

@vmihailenco thx for comments :) Its also good idea, but i didn't want to return success(empty items) after error occurs.

Anyway, your suggestion is the best way now. thx!!

zacscoding avatar Oct 14 '21 12:10 zacscoding