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.

48 lines
1.2 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*2)),
  23. "Character.nick": dataloader.NewBatchedLoader(characterNickBatch, dataloader.WithWait(time.Millisecond*2)),
  24. },
  25. }
  26. }
  27. // FromContext gets the Loader from context.
  28. func FromContext(ctx context.Context) *Loader {
  29. value := ctx.Value(&contextKey)
  30. if value == nil {
  31. return nil
  32. }
  33. return value.(*Loader)
  34. }
  35. // ToContext gets a context with the loader as a value
  36. func (loader *Loader) ToContext(ctx context.Context) context.Context {
  37. loader.ctx = ctx
  38. return context.WithValue(ctx, &contextKey, loader)
  39. }