GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.3 KiB

  1. package loader
  2. import (
  3. "context"
  4. "errors"
  5. "time"
  6. "github.com/graph-gophers/dataloader"
  7. )
  8. var contextKey struct{}
  9. // ErrNotFound is returned in batches when one or more things weren't found. Usually harmless.
  10. var ErrNotFound = errors.New("not found")
  11. // A Loader is a collection of data loaders and functions to act on them. It's supposed to be
  12. // request-scoped, and will thus keep things cached indefinitely.
  13. type Loader struct {
  14. ctx context.Context
  15. loaders map[string]*dataloader.Loader
  16. }
  17. // New initializes the loader.
  18. func New() *Loader {
  19. return &Loader{
  20. ctx: context.Background(),
  21. loaders: map[string]*dataloader.Loader{
  22. "Character.id": dataloader.NewBatchedLoader(characterIDBatch, dataloader.WithWait(time.Millisecond)),
  23. "Character.nick": dataloader.NewBatchedLoader(characterNickBatch, dataloader.WithWait(time.Millisecond)),
  24. "Channel.name": dataloader.NewBatchedLoader(channelNameBatch, dataloader.WithWait(time.Millisecond)),
  25. },
  26. }
  27. }
  28. // FromContext gets the Loader from context.
  29. func FromContext(ctx context.Context) *Loader {
  30. value := ctx.Value(&contextKey)
  31. if value == nil {
  32. return nil
  33. }
  34. return value.(*Loader)
  35. }
  36. // ToContext gets a context with the loader as a value
  37. func (loader *Loader) ToContext(ctx context.Context) context.Context {
  38. loader.ctx = ctx
  39. return context.WithValue(ctx, &contextKey, loader)
  40. }