collection.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package helper
  2. import (
  3. "fmt"
  4. "github.com/gshopify/service-wrapper/fun"
  5. "github.com/gshopify/service-wrapper/model"
  6. "gshopper.com/gshopify/products/graphql/generated"
  7. )
  8. func NewCollectionConnection(src []*generated.Collection,
  9. after *string, before *string, first *int, last *int, reverse *bool) (*generated.CollectionConnection, error) {
  10. var (
  11. connection = &generated.CollectionConnection{}
  12. err error
  13. )
  14. if len(src) == 0 {
  15. return connection, nil
  16. }
  17. if reverse != nil && *reverse {
  18. src = fun.Reverse(src)
  19. }
  20. connection.Nodes = src[:]
  21. connection.Nodes = fun.First(connection.Nodes, first)
  22. connection.Nodes = fun.Last(connection.Nodes, last)
  23. if connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidCollection, true); err != nil {
  24. return nil, fmt.Errorf("illegal cursor: %s", *after)
  25. }
  26. if connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidCollection, false); err != nil {
  27. return nil, fmt.Errorf("illegal cursor: %s", *before)
  28. }
  29. connection.PageInfo = NewPageInfo(connection.Nodes, model.GidCollection, src[0], src[len(src)-1])
  30. // Edges
  31. for i := range connection.Nodes {
  32. e := &generated.CollectionEdge{
  33. Node: connection.Nodes[i],
  34. }
  35. if c, err := model.NewSimpleCursor(e.Node.ID, model.GidCollection); err == nil {
  36. e.Cursor = *c.String()
  37. }
  38. connection.Edges = append(connection.Edges, e)
  39. }
  40. return connection, nil
  41. }