package loader import ( "context" "errors" "time" "github.com/graph-gophers/dataloader" ) var contextKey struct{} // ErrNotFound is returned in batches when one or more things weren't found. Usually harmless. var ErrNotFound = errors.New("not found") // A Loader is a collection of data loaders and functions to act on them. It's supposed to be // request-scoped, and will thus keep things cached indefinitely. type Loader struct { ctx context.Context loaders map[string]*dataloader.Loader } // New initializes the loader. func New() *Loader { return &Loader{ ctx: context.Background(), loaders: map[string]*dataloader.Loader{ "Character.id": dataloader.NewBatchedLoader(characterIDBatch, dataloader.WithWait(time.Millisecond)), "Character.nick": dataloader.NewBatchedLoader(characterNickBatch, dataloader.WithWait(time.Millisecond)), "Channel.name": dataloader.NewBatchedLoader(channelNameBatch, dataloader.WithWait(time.Millisecond)), }, } } // FromContext gets the Loader from context. func FromContext(ctx context.Context) *Loader { value := ctx.Value(&contextKey) if value == nil { return nil } return value.(*Loader) } // ToContext gets a context with the loader as a value func (loader *Loader) ToContext(ctx context.Context) context.Context { loader.ctx = ctx return context.WithValue(ctx, &contextKey, loader) }