1- // package lru_cache_test contains an exmaple of using go-cache as a long term cache solution for dataloader.
2- package lru_cache_test
1+ package dataloader_test
32
43import (
54 "context"
@@ -10,40 +9,35 @@ import (
109 lru "github.com/hashicorp/golang-lru"
1110)
1211
13- // Cache implements the dataloader.Cache interface
14- type cache [K comparable , V any ] struct {
12+ type lruCacheAdapter [K comparable , V any ] struct {
1513 * lru.ARCCache
1614}
1715
18- // Get gets an item from the cache
19- func (c * cache [K , V ]) Get (_ context.Context , key K ) (dataloader.Thunk [V ], bool ) {
16+ func (c * lruCacheAdapter [K , V ]) Get (_ context.Context , key K ) (dataloader.Thunk [V ], bool ) {
2017 v , ok := c .ARCCache .Get (key )
2118 if ok {
2219 return v .(dataloader.Thunk [V ]), ok
2320 }
2421 return nil , ok
2522}
2623
27- // Set sets an item in the cache
28- func (c * cache [K , V ]) Set (_ context.Context , key K , value dataloader.Thunk [V ]) {
24+ func (c * lruCacheAdapter [K , V ]) Set (_ context.Context , key K , value dataloader.Thunk [V ]) {
2925 c .ARCCache .Add (key , value )
3026}
3127
32- // Delete deletes an item in the cache
33- func (c * cache [K , V ]) Delete (_ context.Context , key K ) bool {
28+ func (c * lruCacheAdapter [K , V ]) Delete (_ context.Context , key K ) bool {
3429 if c .ARCCache .Contains (key ) {
3530 c .ARCCache .Remove (key )
3631 return true
3732 }
3833 return false
3934}
4035
41- // Clear clears the cache
42- func (c * cache [K , V ]) Clear () {
36+ func (c * lruCacheAdapter [K , V ]) Clear () {
4337 c .ARCCache .Purge ()
4438}
4539
46- func ExampleGolangLRU () {
40+ func ExampleNewBatchedLoader_golangLRU () {
4741 type User struct {
4842 ID int
4943 Email string
@@ -57,19 +51,16 @@ func ExampleGolangLRU() {
5751
5852 batchFunc := func (_ context.Context , keys []int ) []* dataloader.Result [* User ] {
5953 var results []* dataloader.Result [* User ]
60- // do some pretend work to resolve keys
6154 for _ , k := range keys {
6255 results = append (results , & dataloader.Result [* User ]{Data : m [k ]})
6356 }
6457 return results
6558 }
6659
67- // go-cache will automatically cleanup expired items on given duration.
6860 c , _ := lru .NewARC (100 )
69- cache := & cache [int , * User ]{ARCCache : c }
70- loader := dataloader .NewBatchedLoader (batchFunc , dataloader.WithCache [int , * User ](cache ))
61+ adapter := & lruCacheAdapter [int , * User ]{ARCCache : c }
62+ loader := dataloader .NewBatchedLoader (batchFunc , dataloader.WithCache [int , * User ](adapter ))
7163
72- // immediately call the future function from loader
7364 result , err := loader .Load (context .TODO (), 5 )()
7465 if err != nil {
7566 // handle error
0 commit comments