product.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 NewProductConnection(src []*generated.Product,
  9. after *string, before *string, first *int, last *int, reverse *bool) (*generated.ProductConnection, error) {
  10. var (
  11. connection = &generated.ProductConnection{}
  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. connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidProduct, true)
  24. if err != nil {
  25. return nil, fmt.Errorf("illegal cursor: %s", *after)
  26. }
  27. connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidProduct, false)
  28. if err != nil {
  29. return nil, fmt.Errorf("illegal cursor: %s", *before)
  30. }
  31. connection.PageInfo = NewPageInfo(connection.Nodes, model.GidProduct, src[0], src[len(src)-1])
  32. // Edges
  33. for i := range connection.Nodes {
  34. e := &generated.ProductEdge{
  35. Node: connection.Nodes[i],
  36. }
  37. if c, err := model.NewSimpleCursor(e.Node.ID, model.GidCollection); err == nil {
  38. e.Cursor = *c.String()
  39. }
  40. connection.Edges = append(connection.Edges, e)
  41. }
  42. return connection, nil
  43. }