项目作者: graph-gophers

项目描述 :
Implementation of Facebook's DataLoader in Golang
高级语言: Go
项目地址: git://github.com/graph-gophers/dataloader.git
创建时间: 2016-11-23T17:40:48Z
项目社区:https://github.com/graph-gophers/dataloader

开源协议:MIT License

下载


DataLoader

GoDoc
Build Status

This is an implementation of Facebook’s DataLoader in Golang.

Install

go get -u github.com/graph-gophers/dataloader/v7

Usage

  1. // setup batch function - the first Context passed to the Loader's Load
  2. // function will be provided when the batch function is called.
  3. // this function is registered with the Loader, and the key and value are fixed using generics.
  4. batchFn := func(ctx context.Context, keys []int) []*dataloader.Result[*User] {
  5. var results []*dataloader.Result[*User]
  6. // do some async work to get data for specified keys
  7. // append to this list resolved values
  8. return results
  9. }
  10. // create Loader with an in-memory cache
  11. loader := dataloader.NewBatchedLoader(batchFn)
  12. /**
  13. * Use loader
  14. *
  15. * A thunk is a function returned from a function that is a
  16. * closure over a value (in this case an interface value and error).
  17. * When called, it will block until the value is resolved.
  18. *
  19. * loader.Load() may be called multiple times for a given batch window.
  20. * The first context passed to Load is the object that will be passed
  21. * to the batch function.
  22. */
  23. thunk := loader.Load(context.TODO(), 5)
  24. result, err := thunk()
  25. if err != nil {
  26. // handle data error
  27. }
  28. log.Printf("value: %#v", result)

Don’t need/want to use context?

You’re welcome to install the v1 version of this library.

Cache

This implementation contains a very basic cache that is intended only to be used for short lived DataLoaders (i.e. DataLoaders that only exist for the life of an http request). You may use your own implementation if you want.

it also has a NoCache type that implements the cache interface but all methods are noop. If you do not wish to cache anything.

Examples

There are a few basic examples in the example folder.

See also