collection.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "sort"
  8. )
  9. func NewCollectionConnection(src []*generated.Collection,
  10. after *string, before *string, first *int, last *int, reverse *bool) (*generated.CollectionConnection, error) {
  11. var (
  12. connection = &generated.CollectionConnection{}
  13. err error
  14. )
  15. if len(src) == 0 {
  16. return connection, nil
  17. }
  18. if reverse != nil && *reverse {
  19. src = fun.Reverse(src)
  20. }
  21. connection.Nodes = src[:]
  22. connection.Nodes = fun.First(connection.Nodes, first)
  23. connection.Nodes = fun.Last(connection.Nodes, last)
  24. if connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidCollection, true); err != nil {
  25. return nil, fmt.Errorf("illegal cursor: %s", *after)
  26. }
  27. if connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidCollection, false); err != nil {
  28. return nil, fmt.Errorf("illegal cursor: %s", *before)
  29. }
  30. connection.PageInfo = model.NewPageInfo(connection.Nodes, model.GidCollection, src[0], src[len(src)-1])
  31. // Edges
  32. for i := range connection.Nodes {
  33. e := &generated.CollectionEdge{
  34. Node: connection.Nodes[i],
  35. }
  36. if c, err := model.NewCursor(e.Node.ID, model.GidCollection); err == nil {
  37. e.Cursor = *c.String()
  38. }
  39. connection.Edges = append(connection.Edges, e)
  40. }
  41. return connection, nil
  42. }
  43. // SortCollections TODO: CollectionSortKeysRelevance
  44. func SortCollections(src []*generated.Collection, sortKey *generated.CollectionSortKeys) []*generated.Collection {
  45. if sortKey == nil || !sortKey.IsValid() {
  46. return src[:]
  47. }
  48. sort.Slice(src[:], func(i, j int) bool {
  49. switch *sortKey {
  50. case generated.CollectionSortKeysID:
  51. return src[i].ID < src[j].ID
  52. case generated.CollectionSortKeysTitle:
  53. return src[i].Title < src[j].Title
  54. case generated.CollectionSortKeysUpdatedAt:
  55. return src[i].UpdatedAt < src[j].UpdatedAt
  56. }
  57. return false
  58. })
  59. return src[:]
  60. }